Leetcode -- Sudoku Solver
来源:互联网 发布:怎么校准网络时间 编辑:程序博客网 时间:2024/05/02 02:29
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.
分析:
首先意识到这是个递归的结构:每次添加一个数,相当于一个新的board;
求解时,对每个需要填充的位置,找到一个合法的数,并以此为新的board,进行递归求解。这时可能出现三种情况:
1. 找不到需要填充的位置,也即整个board都被正确的填充了,求解完成;
2. 在某个位置上可以一直找到最终的解,这时返回true;
3. 在某个位置上找不到任何可以填充的数,这说明之前的某一步是不合法的,直接返回false;
class Solution {public: bool check(vector<vector<char>>& board,int x,int y) { for(int i=0;i<9;++i)//row x { if(i==y) continue; if(board[x][i]==board[x][y]) return 0; } for(int i=0;i<9;++i) { if(i==x) continue; if(board[i][y]==board[x][y]) return 0; } int px = (x/3)*3,py=(y/3)*3; for(int i=0;i<3;++i) for(int j=0;j<3;++j) { if(px+i==x&&py+j==y) continue; if(board[px+i][py+j]==board[x][y]) return 0; } return 1; } bool solve(vector<vector<char>>& board) { for(int i=0;i<9;++i) for(int j=0;j<9;++j) if(board[i][j]=='.') { for(char x='1';x<='9';++x) { board[i][j]=x; if(check(board,i,j)&&solve(board)) return 1; board[i][j]='.'; } return 0; } return 1; } void solveSudoku(vector<vector<char>>& board) { solve(board); }};
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)
- 10月24日与10月25日笔记题
- [iOS]Status bar hidden
- 【Android成长之路】最常用和最难用的控件——ListView的浅谈(提升ListView 的运行效率)
- 将构造函数的作用域赋给新的对象
- 了解External Accessory Framework之EAAccessory
- Leetcode -- Sudoku Solver
- Esper学习——Esper介绍
- 恐龙快跑(Flappy T-Rex)
- dorado环境搭建
- apache 代理tomcat 和指定503页面
- 解决win8.1下的msi文件安装报2503,2502问题
- Esper——事件类型
- MySQL锁机制及优化
- Expires