码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode#37 Sudoku Solver

时间:2015-01-23 18:08:44      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

回溯,没啥好说的

 

 1 bool row[9][9];
 2 bool col[9][9];
 3 bool grid[9][9];
 4 bool mark[9][9];
 5 
 6 bool solve(vector<vector<char> > &board, int r, int c) {
 7   if (r == 9)
 8     return true;
 9   if (mark[r][c])
10     return solve(board, r + (c + 1) / 9, (c + 1) % 9);
11   for (int i = 0; i < 9; i++) {
12     if (!row[r][i] && !col[c][i] && !grid[(r / 3) * 3 + c / 3][i]) {
13       row[r][i] = col[c][i] = grid[(r / 3) * 3 + c / 3][i] = true;
14       board[r][c] = i + 1;
15       if (solve(board, r + (c + 1) / 9, (c + 1) % 9))
16         return true;
17       board[r][c] = .;
18       row[r][i] = col[c][i] = grid[(r / 3) * 3 + c / 3][i] = false;
19     }
20   }
21 
22   return false;
23 }
24 
25 void solveSudoku(vector<vector<char> > &board) {
26   memset(row, 9 * 9 * sizeof(bool), false);
27   memset(col, 9 * 9 * sizeof(bool), false);
28   memset(grid, 9 * 9 * sizeof(bool), false);
29   memset(mark, 9 * 9 * sizeof(bool), false);
30 
31   for (int r = 0; r < 9; r++)
32     for (int c = 0; c < 9; c++)
33       if (board[r][c] != .) {
34         row[r][board[r][c] - 1]
35           = col[c][board[r][c] - 1]
36           = grid[(r / 3) * 3 + c / 3][board[r][c] - 1]
37           = mark[r][c]
38           = true;
39       }
40 
41   solve(board, 0, 0);
42 }

 

Leetcode#37 Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/boring09/p/4244479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!