/************************************************ Grundlegende Algorithmen mit Java, http://algorithmen-und-problemloesungen.de/ Copyright @2007-2009 by Doina Logofatu in C#: Michael Gärtner ************************************************/ using System; using System.IO; namespace Logofatu { class P09PhotoProblem { private static String FileInputName = "foto.in"; private static String FileOutputName = "foto.out"; private int m, n; private int[,] a; public P09PhotoProblem(int[,] a, int m, int n) { this.a = a; this.m = m; this.n = n; } private void color(int i, int j, int col) { if ( 0 <= i && i < m && 0 <= j && j < n && 1 == a[i, j] ) { a[i, j] = col; color(i, j - 1, col); color(i, j + 1, col); color(i - 1, j, col); color(i + 1, j, col); } } void run(StreamWriter sw) { int col = 1; for ( int i = 0; i < m; i++ ) for ( int j = 0; j < n; j++ ) if ( 1 == a[i, j] ) color(i, j, ++col); sw.WriteLine(col-1); for ( int i = 0; i < m; i++ ) { for ( int j = 0; j < n; j++ ) { sw.Write(a[i,j]); sw.Write(' '); } sw.WriteLine(); } } static void Main(string[] args) { StreamReader sr = null; StreamWriter sw = null; try { sw = new StreamWriter(FileOutputName); sr = new StreamReader(FileInputName); string[] sArray = sr.ReadLine().Split(' '); int m = int.Parse(sArray[0]); int n = int.Parse(sArray[1]); int[,] a = new int[m, n]; for ( int i = 0; i < m; i++ ) { sArray = sr.ReadLine().Split(' '); for ( int j = 0; j < n; j++ ) a[i, j] = int.Parse(sArray[j]); } new P09PhotoProblem(a, m, n).run(sw); } finally { if ( sr != null ) { sr.Close(); } if ( sw != null ) { sw.Close(); } } } } }