leetcode: Sudoku Solver
2013-11-04 10:55
453 查看
http://oj.leetcode.com/problems/sudoku-solver/
思路:
和前面一题Valid Sudoku相比,题目的输入保证是有效的。这样用回溯法我们只要检查新加入的值能否在行、列以及小方块里有效即可,没有必要检查整个矩阵。
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相比,题目的输入保证是有效的。这样用回溯法我们只要检查新加入的值能否在行、列以及小方块里有效即可,没有必要检查整个矩阵。
class Solution { public: bool isValidSudoku(vector<vector<char> > &board, int x, int y) { int row, col; // Same value in the same column? for (row = 0; row < 9; ++row) { if ((x != row) && (board[row][y] == board[x][y])) { return false; } } // Same value in the same row? for (col = 0; col < 9; ++col) { if ((y != col) && (board[x][col] == board[x][y])) { return false; } } // Same value in the 3 * 3 block it belong to? for (row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) { for (col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) { if ((x != row) && (y != col) && (board[row][col] == board[x][y])) { return false; } } } return true; } bool internalSolveSudoku(vector<vector<char> > &board) { for (int row = 0; row < 9; ++row) { for (int col = 0; col < 9; ++col) { if ('.' == board[row][col]) { for (int i = 1; i <= 9; ++i) { board[row][col] = '0' + i; if (isValidSudoku(board, row, col)) { if (internalSolveSudoku(board)) { return true; } } board[row][col] = '.'; } return false; } } } return true; } void solveSudoku(vector<vector<char> > &board) { internalSolveSudoku(board); } };
相关文章推荐
- LeetCode:Valid Sudoku,Sudoku Solver(数独游戏)
- LeetCode :Sudoku Solver
- Java for LeetCode 037 Sudoku Solver
- LeetCode(37) Sudoku Solver
- leetcode--Sudoku Solver
- leetcode 37: Sudoku Solver
- LeetCode 37 Sudoku Solver
- LeetCode 037 Sudoku Solver
- LeetCode-Sudoku Solver
- Leetcode: Sudoku Solver
- LeetCode - Sudoku Solver
- leetcode-37-sudoku solver
- Leetcode 笔记 36 - Sudoku Solver
- leetcode--37--Sudoku Solver
- LeetCode:Valid Sudoku,Sudoku Solver(数独游戏)
- LeetCode_37 Sudoku Solver
- LeetCode 36 Sudoku Solver
- LeetCode37 Sudoku Solver
- [LeetCode]Sudoku Solver
- leetcode[37]Sudoku Solver