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

037. Sudoku Solver

时间:2016-09-09 13:31:51      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

 1 class Solution {
 2 public:
 3     void solveSudoku(vector<vector<char>>& board) {
 4         Sudoku(board);
 5     }
 6 private:
 7     bool Sudoku(vector<vector<char>>& board)
 8     {
 9         for (int i = 0; i < 9; ++i) {
10             for (int j = 0; j < 9; ++j) {
11                 if (board[i][j] == .) {
12                     for (int k = 0; k < 9; ++k) {
13                         board[i][j] = 1 + k;
14                         if (isValid(board, i, j) && Sudoku(board)) return true;
15                         board[i][j] = .;
16                     }
17                     return false;
18                 }
19             }
20         }
21         return true;
22     }
23     bool isValid(vector<vector<char>>& board, int i, int j)
24     {
25         for (int index = 0; index < 9; ++index) {
26             if (index != j && board[i][index] == board[i][j]) return false;
27         }
28         for (int index = 0; index < 9; ++index) {
29             if (index != i && board[index][j] == board[i][j]) return false;
30         }
31         for (int row = 3 * (i / 3); row < 3 * (i / 3) + 3; ++row) {
32             for (int col = 3 * (j / 3); col < 3 * (j / 3) + 3; ++col) {
33                 if ((row != i || col != j) && board[row][col] == board[i][j]) return false;
34             }
35         }
36         return true;
37     }
38 };

 

037. Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/shadowwalker9/p/5856179.html

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