[Leetcode] Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

A sudoku puzzle...

 

...and its solution numbers marked in red.

 

暴力DFS!

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

 

posted @ 2014-04-13 22:25  Eason Liu  阅读(1418)  评论(0编辑  收藏  举报