LeetCode | Sudoku Solver
来源:互联网 发布:汤灿到底怎么了知乎 编辑:程序博客网 时间:2024/06/05 08:42
You may assume that there will be only one unique solution.
A sudoku puzzle…
…and its solution numbers marked in red.
数独问题,暴力深搜。
注意在找到解之后,要及时return,以及在第某一行无解的时候,要及时return,这样剪枝才不会导致超时。
class Solution {public: int steps=0; void solveSudoku(vector<vector<char>>& board) { int m=board.size(); if(m==0) return; int n=board[0].size(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(board[i][j]=='.') steps++; } } solveSudoku(0,board); } bool valid(vector<vector<char>>& board,int x,int y){ for(int i=0;i<9;i++){ if(i!=y && board[x][y]==board[x][i]) return false; } for(int i=0;i<9;i++){ if(i!=x && board[x][y]==board[i][y]) return false; } for(int i=0;i<9;i++){ if(i!=y && board[x][y]==board[x][i]) return false; } for(int i=3*(x/3);i<3*(x/3+1);i++){ for(int j=3*(y/3);j<3*(y/3+1);j++){ if((i!=x && j!=y) &&board[i][j]==board[x][y]){ return false; } } } return true; } bool solveSudoku(int step,vector<vector<char>>& board){ if(step==steps){ return true; } //从第一行第一列开始,寻找为.的点 for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ if(board[i][j]=='.'){ //尝试1~9所有的数并看看有无冲突 for(int k=1;k<=9;k++){ board[i][j]=k+'0'; if(valid(board,i,j) && solveSudoku(step+1,board)) //及时退出 return true; board[i][j]='.'; } //及时退出 return false; } } } return true; }};
0 0
- 【LeetCode】Valid Sudoku && Sudoku Solver
- [Leetcode]Sudoku Solver&&Valid Sudoku
- leetcode Valid Sudoku & Sudoku Solver
- Leetcode 37 Sudoku Solver
- [Leetcode] Sudoku Solver
- Leetcode 37: Sudoku solver
- LeetCode Sudoku Solver
- [LeetCode]Sudoku Solver
- Leetcode Sudoku Solver
- LeetCode-Sudoku Solver
- LeetCode - Sudoku Solver
- LeetCode:Sudoku Solver
- 【leetcode】Sudoku Solver
- Leetcode: Sudoku Solver
- leetcode Sudoku Solver
- LeetCode | Sudoku Solver
- LeetCode Sudoku Solver
- [Leetcode] Sudoku Solver (Java)
- JUC——CLH队列锁
- Android声音管理AudioManager使用
- Android自定义的SwitchButton按钮,自己喜欢的风格
- APP升级,获取AppStore版本号和本地版本号--Swift
- RxJava响应式函数编程
- LeetCode | Sudoku Solver
- 使用C语言操作Sqlite数据库
- Lucas+阶乘打表+费马小定理模板
- 从网页抓取城市间的距离
- Runtime学习与使用(一):为UITextField添加类目实现被键盘遮住后视图上移
- HDU 2203 循环串匹配
- js判断手机,邮箱格式是否正确
- event.getX()、event.getY()与event.getRawX()、event.getRawY()的区别
- mac安装mongodb