LeetCode Online Judge 题目C# 练习 - Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

 1         public static bool ValidSudoku(List<List<char>> board)
 2         {
 3             for (int i = 0; i < board.Count; i++)
 4             {
 5                 for (int j = 0; j < board[0].Count; j++)
 6                 {
 7                     if (board[i][j] != '.')
 8                         if (!isValid(board, i, j))
 9                             return false;
10                 }
11             }
12 
13         public static bool isValid(List<List<char>> board, int r, int c)
14         {
15             //////////////CHECK ROW/////////////////////
16             bool[] Row = new bool[9];
17             for (int i = 0; i < 9; i++)
18             {
19                 if (board[r][i] >= '1' && board[r][i] <= '9')
20                 {
21                     if (Row[board[r][i] - '1'] == false)
22                         Row[board[r][i] - '1'] = true;
23                     else
24                         return false;
25                 }
26             }
27 
28             /////////////CHECK COLUMN//////////////////
29             bool[] Col = new bool[9];
30             for (int i = 0; i < 9; i++)
31             {
32                 if (board[i][c] >= '1' && board[i][c] <= '9')
33                 {
34                     if (Col[board[i][c] - '1'] == false)
35                         Col[board[i][c] - '1'] = true;
36                     else
37                         return false;
38                 }
39             }
40 
41             /////////////CHECK GRID///////////////////
42             bool[] Grid = new bool[9];
43             // r / 3 * 3 = beginning row number of that grid
44             // c / 3 * 3 = beginning column number of that grid
45             for (int i = (r / 3) * 3; i < (r / 3) * 3 + 3; i++)
46             {
47                 for (int j = (c / 3) * 3; j < (c / 3) * 3 + 3; j++)
48                 {
49                     if (board[i][j] >= '1' && board[i][j] <= '9')
50                     {
51                         if (Grid[board[i][j] - '1'] == false)
52                             Grid[board[i][j] - '1'] = true;
53                         else
54                             return false;
55                     }
56                 }
57             }
58 
59             return true;
60         }
61            

代码分析:

  不就是前面一题的helper function吗?

posted @ 2012-10-23 03:45  ETCOW  阅读(546)  评论(0编辑  收藏  举报