Leetcode Sudoku Solver9
来源:互联网 发布:张宇唱功知乎 编辑:程序博客网 时间:2024/04/29 14:18
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.
Solve the problem on leetcode
class Solution {
public:
void solveSudoku(vector<vector<char> > &board)
{
//类似于queen
//需要一个res存储空格的位置x*col+y
if(board.empty()) return;
vector<int> res;
int row=board.size();
int col=board[0].size();
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
{
if(board[i][j]=='.')
res.push_back(i*col+j);
}
//空格个数来计算截止条件
int len=res.size();
dfs(board,res,0,len);
}
//cur位置
bool dfs(vector<vector<char> > &board,vector<int> res,int cur,int pos)
{
if(pos==cur) return true;
// int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int index=res[cur];
int x=index/9;
int y=index%9;
//位置up down left right:
for(int i=1;i<=9;i++)
{
if(isvalid(board,x,y,i))
{
board[x][y]=(char)(i+'0');
if(dfs(board,res,cur+1,pos)) return true;
board[x][y]='.';
}
}
return false;
}
bool isvalid(vector<vector<char>> &board,int x,int y,int value)
{
for(int i=0;i<9;i++)
{
if(board[i][y]==char(value+'0')) return false;
if(board[x][i]==char(value+'0')) return false;
int row_s=3*(x/3)+i/3;
int col_s=3*(y/3)+i%3;
if(board[row_s][col_s]==value+'0') return false;
}
return true;
}
};
参考:http://blog.csdn.net/u011095253/article/details/9158497
- Leetcode Sudoku Solver9
- leetCode SudoKu
- leetcode sudoku
- 【LeetCode】Valid Sudoku && Sudoku Solver
- [Leetcode]Sudoku Solver&&Valid Sudoku
- leetcode Valid Sudoku & Sudoku Solver
- LeetCode : Valid Sudoku
- Leetcode 37 Sudoku Solver
- [Leetcode] Sudoku Solver
- Leetcode 37: Sudoku solver
- LeetCode Sudoku Solver
- [LeetCode]Sudoku Solver
- [LeetCode]Valid Sudoku
- Leetcode Sudoku Solver
- [leetcode] Valid Sudoku
- LeetCode-Valid Sudoku
- LeetCode-Sudoku Solver
- LeetCode Valid Sudoku
- Hadoop升级方案(二):从Hadoop 1.0升级到2.0(1)
- RS485接口标准、硬件电路
- hadoop2升级的那点事情(详解)
- RS422接口标准、硬件电路
- hadoop2.7.0升级到2.7.1,版本升级
- Leetcode Sudoku Solver9
- hdoj1237简单计算器
- STL中map的operator[ ]使用方法
- Flash芯片的种类与区别
- [线性DP]轮渡问题(LIS应用)
- Audio驱动开发 之 音频链路学习笔记
- 三种ViewController跳转的异同
- POJ 3050
- linux磁盘分区问题