leetcode: Sudoku Solver
http://oj.leetcode.com/problems/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.
思路:
和前面一题Valid Sudoku相比,题目的输入保证是有效的。这样用回溯法我们只要检查新加入的值能否在行、列以及小方块里有效即可,没有必要检查整个矩阵。
1 class Solution { 2 public: 3 bool isValidSudoku(vector<vector<char> > &board, int x, int y) { 4 int row, col; 5 6 // Same value in the same column? 7 for (row = 0; row < 9; ++row) { 8 if ((x != row) && (board[row][y] == board[x][y])) { 9 return false; 10 } 11 } 12 13 // Same value in the same row? 14 for (col = 0; col < 9; ++col) { 15 if ((y != col) && (board[x][col] == board[x][y])) { 16 return false; 17 } 18 } 19 20 // Same value in the 3 * 3 block it belong to? 21 for (row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) { 22 for (col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) { 23 if ((x != row) && (y != col) && (board[row][col] == board[x][y])) { 24 return false; 25 } 26 } 27 } 28 29 return true; 30 } 31 32 bool internalSolveSudoku(vector<vector<char> > &board) { 33 for (int row = 0; row < 9; ++row) { 34 for (int col = 0; col < 9; ++col) { 35 if ('.' == board[row][col]) { 36 for (int i = 1; i <= 9; ++i) { 37 board[row][col] = '0' + i; 38 39 if (isValidSudoku(board, row, col)) { 40 if (internalSolveSudoku(board)) { 41 return true; 42 } 43 } 44 45 board[row][col] = '.'; 46 } 47 48 return false; 49 } 50 } 51 } 52 53 return true; 54 } 55 56 void solveSudoku(vector<vector<char> > &board) { 57 internalSolveSudoku(board); 58 } 59 };