-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path036_Valid_Sudoku_002.c
104 lines (97 loc) · 2.12 KB
/
036_Valid_Sudoku_002.c
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
void clearFlagArray(int *flagArray, int size)
{
for(int i = 0; i < size; i++)
flagArray[i] = 0;
}
bool isRowValid(char** board, int boardRowSize, int boardColSize, int *flagArray)
{
for(int i = 0; i < boardRowSize; i++)
{
for(int j = 0; j < boardColSize; j++)
{
if(board[i][j] >= '1' && boardColSize <= '9')
{
int index = board[i][j] - '1';
if(flagArray[index])
return false;
else
flagArray[index] = 1;
}
}
clearFlagArray(flagArray, 9);
}
return true;
}
bool isColValid(char** board, int boardRowSize, int boardColSize, int *flagArray)
{
for(int i = 0; i < boardColSize; i++)
{
for(int j = 0; j < boardRowSize; j++)
{
if(board[j][i] >= '1' && boardColSize <= '9')
{
int index = board[j][i] - '1';
if(flagArray[index])
return false;
else
flagArray[index] = 1;
}
}
clearFlagArray(flagArray, 9);
}
return true;
}
bool isGridValid(char** board, int boardRowSize, int boardColSize, int *flagArray)
{
for(int i = 0; i < boardRowSize; i += 3)
{
for(int j = 0; j < boardColSize; j += 3)
{
for(int k = 0; k < 3; k++)
{
int m = i + k;
for(int l = 0; l < 3; l++)
{
int n = j + l;
if(board[m][n] >= '1' && board[m][n] <= '9')
{
int index = board[m][n] - '1';
if(flagArray[index])
return false;
else
flagArray[index] = 1;
}
}
}
clearFlagArray(flagArray, 9);
}
}
return true;
}
bool isValidSudoku(char** board, int boardRowSize, int boardColSize)
{
if(!board || boardRowSize != 9 || boardColSize != 9)
return false;
int *flagArray = (int *)malloc(sizeof(int) * 9);
clearFlagArray(flagArray, 9);
bool flag = isRowValid(board, boardRowSize, boardColSize, flagArray);
if(!flag)
{
free(flagArray);
return false;
}
flag = isColValid(board, boardRowSize, boardColSize, flagArray);
if(!flag)
{
free(flagArray);
return false;
}
flag = isGridValid(board, boardRowSize, boardColSize, flagArray);
if(!flag)
{
free(flagArray);
return false;
}
free(flagArray);
return true;
}