-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathSudokuSolver.cs
executable file
·88 lines (85 loc) · 4.8 KB
/
SudokuSolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Source : https://leetcode.com/problems/sudoku-solver/
// Author : codeyu
// Date : Monday, October 17, 2016 7:38:31 PM
/**********************************************************************************
*
* Write a program to solve a Sudoku puzzle by filling the empty cells.
*
* Empty cells are indicated by the character '.'.
*
* You may assume that there will be only one unique solution.
*
*
*
* A sudoku puzzle...
*
*
*
*
* ...and its solution numbers marked in red.
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
public class Solution037
{
public static char[,] SolveSudoku(char[,] board)
{
if(board.Length != 81 || board.GetLength(0) != 9)
{
return null;
}
SolveSudoku(board,0,0);
return board;
}
private static bool SolveSudoku(char[,] board, int i, int j)
{
if(i == 9) return true;
if(j >= 9) return SolveSudoku(board,i + 1, 0);
if(board[i,j] == '.')
{
for(int k=1;k<=9;k++)
{
board[i,j] = (char)(k+'0');
if(IsValid(board,i,j))
{
if(SolveSudoku(board,i,j+1))
return true;
}
}
}
else
{
return SolveSudoku(board,i,j+1);
}
board[i,j] = '.';
return false;
}
private static bool IsValid(char[,] board, int i, int j)
{
for(int k=0;k<9;k++)
{
if(k!=j && board[i,k]==board[i,j])
return false;
}
for(int k=0;k<9;k++)
{
if(k!=i && board[k,j]==board[i,j])
return false;
}
for(int row = i/3*3; row<i/3*3+3; row++)
{
for(int col=j/3*3; col<j/3*3+3; col++)
{
if((row!=i || col!=j) && board[row,col]==board[i,j])
return false;
}
}
return true;
}
}
}