-
Notifications
You must be signed in to change notification settings - Fork 25
/
Valid_Sudoku.cs
83 lines (70 loc) · 1.92 KB
/
Valid_Sudoku.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
using System.Collections.Generic;
using System.Linq;
using System;
using System.Text;
using Common;
namespace ValidSudoku
{
/// <summary>
/// more on https://github.com/pakosel/leetcode-solutions
/// </summary>
public class Solution
{
int[][] sudoku = null;
public bool IsValidSudoku(char[][] board)
{
sudoku = ConvertBoard(board);
for (int i = 0; i < 9; i++)
{
bool[] arr = new bool[9];
for (int j = 0; j < 9; j++)
if (!Validate(ref arr, sudoku[i][j]))
return false;
}
for (int i = 0; i < 9; i++)
{
bool[] arr = new bool[9];
for (int j = 0; j < 9; j++)
if (!Validate(ref arr, sudoku[j][i]))
return false;
}
for (int i = 0; i < 9; i += 3)
for (int j = 0; j < 9; j += 3)
if (!ValidateSquare(i, j))
return false;
return true;
}
private bool ValidateSquare(int i_start, int j_start)
{
bool[] arr = new bool[9];
for (int i = i_start; i < i_start + 3; i++)
for (int j = j_start; j < j_start + 3; j++)
if (!Validate(ref arr, sudoku[j][i]))
return false;
return true;
}
private bool Validate(ref bool[] arr, int val)
{
if (val == 0)
return true;
val--;
if (val < 0 || val > 9)
return false;
if (arr[val])
return false;
arr[val] = true;
return true;
}
private int[][] ConvertBoard(char[][] board)
{
int[][] res = new int[9][];
for (int i = 0; i < 9; i++)
{
res[i] = new int[9];
for (int j = 0; j < 9; j++)
res[i][j] = board[i][j] == '.' ? 0 : board[i][j] - '0';
}
return res;
}
}
}