[leetcode] 37. Sudoku Solver 解题报告
2015-12-21 16:22
357 查看
题目链接:https://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.
思路:和八皇后思路差不多,每一个坑枚举所有的可能,如果一个位置已经有数字了,则跳过这个位置,进入下一个位置,直到一个分支最后可以得到一个解。
代码如下:
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.
思路:和八皇后思路差不多,每一个坑枚举所有的可能,如果一个位置已经有数字了,则跳过这个位置,进入下一个位置,直到一个分支最后可以得到一个解。
代码如下:
class Solution { public: bool DFS(vector<vector<char>>& board, int y, int x) { if(y == 9) return true; if(x == 9) return DFS(board, y+1, 0); if(board[y][x] != '.') return DFS(board, y, x+1); for(int i = 1, a, b; i <= 9; i++) { for(a=0; a<9; a++) if(board[y][a]=='0'+i) break; if(a != 9) continue; for(a=0; a<9; a++) if(board[a][x]=='0'+i) break; if(a != 9) continue; for(a = y/3*3; a < y/3*3+3; a++) { for(b = x/3*3; b < x/3*3+3; b++) if(board[a][b] == '0'+i) break; if(b!=x/3*3+3) break; } if(!(a == y/3*3+3 && b==x/3*3+3)) continue; board[y][x] = '0' + i; if(DFS(board, y, x+1)) return true; board[y][x] = '.'; } return false; } void solveSudoku(vector<vector<char>>& board) { DFS(board, 0, 0); } };
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- leetcode----Longest Substring Without Repeating Characters
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- [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