Sudoku

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sudoku
{
class Program
{
static void Main(string[] args)
{
int[,] puzzle = {
{ 3, 2, 1, 7, 0, 4, 0, 0, 0 },
{ 6, 4, 0, 0, 9, 0, 0, 0, 7 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 4, 5, 9, 0, 0 },
{ 0, 0, 5, 1, 8, 7, 4, 0, 0 },
{ 0, 0, 4, 9, 6, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 2, 0, 0, 0, 7, 0, 0, 1, 9 },
{ 0, 0, 0, 6, 0, 9, 5, 8, 2 }
};

        if (SolveSudoku(puzzle, 0, 0))
            PrintSudoku(puzzle);
        Console.ReadKey();
            
    }

    public static void PrintSudoku(int[,] puzzle)
    {
        Console.WriteLine("+-----+-----+-----+");

        for (int i = 1; i < 10; ++i)
        {
            for (int j = 1; j < 10; ++j)
                Console.Write("|{0}", puzzle[i - 1, j - 1]);

            Console.WriteLine("|");
            if (i % 3 == 0) Console.WriteLine("+-----+-----+-----+");
        }
    }

    public static bool SolveSudoku(int[,] puzzle, int row, int col)
    {
        if (row < 9 && col < 9)
        {
            if (puzzle[row, col] != 0)
            {
                if ((col + 1) < 9) return SolveSudoku(puzzle, row, col + 1);
                else if ((row + 1) < 9) return SolveSudoku(puzzle, row + 1, 0);
                else return true;
            }
            else
            {
                for (int i = 0; i < 9; ++i)
                {
                    if (IsAvailable(puzzle, row, col, i + 1))
                    {
                        puzzle[row, col] = i + 1;

                        if ((col + 1) < 9)
                        {
                            if (SolveSudoku(puzzle, row, col + 1)) return true;
                            else puzzle[row, col] = 0;
                        }
                        else if ((row + 1) < 9)
                        {
                            if (SolveSudoku(puzzle, row + 1, 0)) return true;
                            else puzzle[row, col] = 0;
                        }
                        else return true;
                    }
                }
            }

            return false;
        }
        else return true;
    }

    private static bool IsAvailable(int[,] puzzle, 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;
    }

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值