/************************************************ Grundlegende Algorithmen mit Java, http://algorithmen-und-problemloesungen.de/ Copyright @2007-2009 by Doina Logofatu in C#: Michael Gärtner ************************************************/ using System; using System.Collections; using System.IO; namespace Logofatu { class P13Sudoku { private static String FileInputName = "sudoku.in"; private static String FileOutputName = "sudoku.out"; private const char V = '*'; private const int N = 3; private const int DIM = N * N; private static int anzahl = 0; private BitArray[] sl; private BitArray[] sc; private BitArray[,] sb; private int[,] v; public P13Sudoku() { sl = new BitArray[DIM]; sc = new BitArray[DIM]; for ( int i = 0; i < DIM; i++ ) { sl[i] = new BitArray(10); sc[i] = new BitArray(10); } sb = new BitArray[N, N]; for ( int i = 0; i < N; i++ ) for ( int j = 0; j < N; j++ ) sb[i, j] = new BitArray(10); v = new int[DIM, DIM]; } bool set(int l, int c, int value) { if ( !sl[l].Get(value) && !sc[c].Get(value) && !sb[l / N, c / N].Get(value) ) { sl[l].Set(value, true); sc[c].Set(value, true); sb[l / N, c / N].Set(value, true); v[l, c] = value; return true; } else return false; } void unset(int l, int c, int value) { sl[l].Set(value, false); sc[c].Set(value, false); sb[l / N, c / N].Set(value, false); v[l, c] = 0; } void run(StreamReader sr, StreamWriter sw) { int l = 0; int c = 0; while ( !sr.EndOfStream && l < DIM ) { string s = sr.ReadLine(); for ( int i = 0; i < s.Length; i++ ) { char ch = s[i]; if ( char.IsDigit(ch) || ch == V ) { if ( ch != V ) { if ( !set(l,c, (int)char.GetNumericValue(ch)) ) return; } if ( DIM == ++c ) { l++; c = 0; } } } } back(0, -1, sw); } private void writeSolution(StreamWriter sw) { for ( int l = 0; l < DIM; l++ ) { sw.Write(v[l, 0]); for ( int c = 1; c < DIM; c++ ) { sw.Write(' '); sw.Write(v[l, c]); } sw.WriteLine(); } sw.WriteLine(); anzahl++; } private void back(int l, int c, StreamWriter sw) { do { c++; if ( c == DIM ) { c = 0; l++; if ( l == DIM ) { writeSolution(sw); return; } } } while ( v[l,c] != 0 ); for ( int value = 1; value <= DIM; ++value ) { if ( set(l,c,value) ) { back(l,c,sw); unset(l,c,value); } } } static void Main(string[] args) { StreamReader sr = null; StreamWriter sw = null; try { sw = new StreamWriter(FileOutputName); sr = new StreamReader(FileInputName); new P13Sudoku().run(sr, sw); } catch ( IOException ex ) { Console.WriteLine("Fehler bei der Dateiverarbeitung!\n" + ex.ToString()); } finally { if ( sr != null ) { sr.Close(); } if ( sw != null ) { Console.WriteLine(anzahl); sw.Close(); } } } } }