代码改变世界

leetcode - Sudoku Solver

2013-12-10 14:26  张汉生  阅读(388)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     bool solveSudoku(vector<vector<char> > & board, vector<vector<vector<bool> > > & flag, int x, int y){
 4     bool wEnd = (x == 8 && y == 8) ? true: false;
 5     int nextX = y<8? x: x+1;
 6     int nextY = y<8? y+1: 0;
 7     if (board[x][y]!='.'){
 8         if (wEnd)
 9         return true;
10         else return (solveSudoku(board, flag, nextX, nextY));
11     }
12     for (int i=0; i<9; i++){
13         int i1 = x;
14         int i2 = y;
15         int i3 = (x/3)*3 + y/3;
16         if (flag[0][i1][i] || flag[1][i2][i] || flag[2][i3][i])
17         continue;
18         board[x][y] = '1'+ i;
19         flag[0][i1][i] = flag[1][i2][i] = flag[2][i3][i] = true;
20         if (wEnd)
21         return true;
22         else if (solveSudoku(board, flag, nextX, nextY))
23         return true;
24         flag[0][i1][i] = flag[1][i2][i] = flag[2][i3][i] = false;
25         board[x][y] = '.';
26     }
27     return false;
28     }
29     void solveSudoku(vector<vector<char> > &board) {
30     vector<bool> vb(9,false);
31     vector<vector<bool> > vvb (9, vb);
32     vector<vector<vector<bool> > > flag(3, vvb);
33     for (int i=0; i<9; i++)
34         for (int j=0; j<9; j++){
35         int i1 = i;
36         int i2 = j;
37         int i3 = (i/3)*3 + j/3;
38         if (board[i][j] != '.'){
39             int index = board[i][j] - '1';
40             flag[0][i1][index] = flag[1][i2][index] = flag[2][i3][index] = true;
41         }
42         }
43     solveSudoku(board, flag, 0, 0);
44     }
45 };