Sudoku solver

CSharp · Console

/Program.cs

using System;
using System.IO;
using System.Diagnostics;

namespace Sudoku
{
	public static class Extensions
    {
        public static bool IsNumeric(this string s)
        {
            foreach (char c in s)
            {
                if (!char.IsDigit(c) && c != '.')
                {
                    return false;
                }
            }

            return true;
        }
    }
	
    class Game
    {
        private int[,] puzzle = new int[9, 9];

        public bool isAvailable(int row, int col, int num)
        {
            int rowStart = (row / 3) * 3;
            int colStart = (col / 3) * 3;

            for (int i = 0; i < 9; ++i)
            {
                if (puzzle[row, i] == num) return false;
                if (puzzle[i, col] == num) return false;
                if (puzzle[rowStart + (i % 3), colStart + (i / 3)] == num) return false;
            }
            return true;
        }
        

        public bool fillSudoku(int row, int col)
        {
            //Debug.WriteLine("fillSudoku called with " + row.ToString() + " " + col.ToString());
            if (row < 9 && col < 9)
            {
                if (puzzle[row, col] != 0)
                {
                    if ((col + 1) < 9) return fillSudoku(row, col + 1);
                    else if ((row + 1) < 9) return fillSudoku(row + 1, 0);
                    else return true;
                }
                else
                {
                    for (int i = 0; i < 9; ++i)
                    {
                        if (isAvailable(row, col, i + 1))
                        {
                            puzzle[row,col] = i + 1;

                            if (fillSudoku(row, col)) return true;
                            else puzzle[row,col] = 0;
                        }
                    }
                }
                return false;
            }
            else return true;
        }

        public void checkSolutions()
        {
            if (!fillSudoku(0, 0))
            {
                Console.Write("\n\nNow Solutions\n\n");
            }
        }

        public void print()
        {
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Write("+-----+-----+-----+\n");
            Console.ForegroundColor = ConsoleColor.White;

            for (int i = 1; i < 10; ++i)
            {
                for (int j = 1; j < 10; ++j)
                {
                    if (j == 1 || j == 4 || j == 7)
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Black;
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.White;
                    }

                    if (puzzle[i - 1, j - 1] != 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Magenta;
                    }
                    Console.Write("{0}", puzzle[i - 1, j - 1]);
                    Console.ForegroundColor = ConsoleColor.White;
                }

                Console.ForegroundColor = ConsoleColor.Blue;
                Console.Write("|\n");
                Console.ForegroundColor = ConsoleColor.White;

                if (i % 3 == 0)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.Write("+-----+-----+-----+\n");
                    Console.ForegroundColor = ConsoleColor.White;
                }
            }
        }

        public void clear()
        {
            for (int i = 0; i < 9; ++i)
            {
                for (int j = 0; j < 9; ++j)
                {
                    puzzle[i, j] = 0;
                }
            }
            Console.Clear();
        }

        public void saveToFile()
        {
            StreamWriter str = new StreamWriter("SUDOKU.txt");
            for (int i = 0; i < 9; ++i)
            {
                for (int j = 0; j < 9; ++j)
                {
                    str.Write(puzzle[i, j] + " ");
                }
                str.Write("\n");
            }
            str.Close();
        }

        public void readFromFile()
        {
            StreamReader str = new StreamReader("SUDOKU.txt");

            if (str == null)
            {
                Console.WriteLine("Отсутствует файл SUDOKU.txt");
            }
            else
            {
                clear();
                for (int i = 0; i < 9; ++i)
                {
                    string[] lineNumbers = str.ReadLine().Split(' ');
                    for(int x = 0;  x < lineNumbers.Length; x++)
                    {
                        if(Extensions.IsNumeric(lineNumbers[x]) == false)
                        {
                            clear();
                            return;
                        }
                    }

                    for (int j = 0; j < 9; ++j)
                    {
                        puzzle[i, j] = Convert.ToInt32(lineNumbers[j]);
                    }
                }
                str.Close();
                
                for (int i = 0; i < 9; ++i)
                {
                    for (int j = 0; j < 9; ++j)
                    {
                        if (puzzle[i, j] < 0 || puzzle[i, j] > 9)
                        {
                            clear();
                            return;
                        }
                    }
                }
            }
        }

        public void MainMenu()
        {
            int reboot = 1;
            
            while (true)
            {
                print();
                Console.Write("###################\n");
                Console.WriteLine("# 1.Заполнить     #\n# 2.Сохранить     #\n# 3.Загрузить     #\n# 4.Очистить      #\n# 5.Найти решение #\n# 0.Выход         #");
                Console.Write("###################\n");
                Console.Write("\nСделайте выбор -> ");
                int choise = Convert.ToInt32(Console.ReadLine());
                switch (choise)
                {
                    case 1:
                        reboot = 1;
                        while (reboot != 0)
                        {
                            try
                            {
                                Console.Write("Введите номер строки (1-9): ");
                                int x = Convert.ToInt32(Console.ReadLine());
                                Console.Write("Введите номер столбца (1-9): ");
                                int y = Convert.ToInt32(Console.ReadLine());
                                Console.Write("Введите цифру (1-9): ");
                                int num = Convert.ToInt32(Console.ReadLine());
                                puzzle[x - 1, y - 1] = num;

                                Console.Write("Добавить еще? (1-Да | 0-Нет) -> ");
                                reboot = Convert.ToInt32(Console.ReadLine());
                            }

                            catch
                            {
                                Console.WriteLine("Вы вышли за пределы нормы!");
                            }
                        }
                        break;
                        
                    case 2:
                        saveToFile();
                        break;

                    case 3:
                        readFromFile();
                        break;

                    case 4:
                        clear();
                        break;

                    case 5:
                        checkSolutions();
                        break;

                    case 0:
                        Environment.Exit(-1);
                        break;
                }
            }
        }
    }
}
;