[LeetCode]037-Sudoku Solver
来源:互联网 发布:电脑翻墙软件 编辑:程序博客网 时间:2024/05/22 15:58
题目:
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.
Solution:
思路,类似于回溯法,层层遍历,直到最后,返回true,否则返回false。
回溯法要注意判断函数,即check,判断当前要插入的值在横向、纵向、子方格内都是合法的。
代码如下:
void solveSudoku(vector<vector<char>>& board) { solve(board); } 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(int k = 1;k<=9;k++) { board[i][j] = k + '0'; if(isValid(board,i,j) && solve(board)) return true; board[i][j] = '.'; } return false; } } } return true; } bool isValid(vector<vector<char>>& board,int row,int col) { int i,j; i = j = 0; for(i =0;i<9;i++) { if(i != row && board[row][col] == board[i][col]) return false; } for(j = 0;j<9;j++) { if(j != col && board[row][col] == board[row][j]) return false; } int grid_row = row/3 * 3; int grid_col = col/3 * 3; for(i =0;i<3;i++) for(j =0;j<3;j++) { if(row != i+grid_row && col != j + grid_col && board[i+grid_row][j+grid_col] == board[row][col]) return false; } return true; }
参考到一个比较简略关键思路清晰的算法:
http://blog.csdn.net/aivin24/article/details/33346657
0 0
- [LeetCode]037-Sudoku Solver
- LeetCode 037 Sudoku Solver
- 【LeetCode】Valid Sudoku && Sudoku Solver
- [Leetcode]Sudoku Solver&&Valid Sudoku
- leetcode Valid Sudoku & Sudoku Solver
- leetcode 037 —— Sudoku Solver
- leetcode解题方案--037-- 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
- 编译MatConvNet window下解决gdiplus库的问题
- mvc中使用伙伴类
- 给 Android 开发者的 RxJava 详解
- C#中的委托和事件
- 第四十一篇:opencv中相关的训练的问题解答(经典)
- [LeetCode]037-Sudoku Solver
- JAVA面向对象之对象和类
- Modernizr.js和yepnode.js
- 【ORACLE】用SYS登录报ORA-28009:connection as SYS should be as SYSDBA OR SYSOPER解决方法
- ORA-12154: TNS:could not resolve the connect identifier specified
- 原码 反码 补码
- Java 开发项目管理工具
- android开发之动画的详解 整理资料 Android开发程序小冰整理
- mysql数据库表的基本操作