LeetCode 37: Sudoku Solver
2015-10-24 21:17
441 查看
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.
解题思路
采用回溯法(Backtracking)求解,代码如下:class Solution { private: // 检测第 x 行,第 y 列是否有效 bool isValidSudoku(vector<vector<char>>& board, int row, int col) { // 行 for(int j = 0; j < 9; j++) if(j != col && board[row][j] == board[row][col]) return false; // 列 for(int i = 0; i < 9; i++) if(i != row && board[i][col] == board[row][col]) return false; // 九宫格 int gridRow = row/3*3, gridCol = col/3*3; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) if(gridRow + i != row && gridCol + j != col && board[gridRow + i][gridCol + j] == board[row][col]) return false; return true; } bool internalSolver(vector<vector<char>>& board) { for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { if (board[i][j] == '.') { // 若board[i][j] == '.',则尝试填入数字1-9 for (int k = 0; k < 9; ++k) { board[i][j] = '1' + k; // 当前填入的数字有效,递归解决余下部分 if (isValidSudoku(board, i, j)) { if (internalSolver(board)) { // 余下部分成功解决,则board已填充完全 return true; } } } //该空格无论设置什么数字都无法达到合法状态,回溯 board[i][j] = '.'; return false; } } } return true; } public: void solveSudoku(vector<vector<char>>& board) { internalSolver(board); } };
这里提供了一个JavaScript实现的 Sudoku puzzle solver 和一些相关链接。
相关文章推荐
- C#避免回溯方法心得
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 回溯算法 图m着色问题
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解