0
点赞
收藏
分享

微信扫一扫

[leetcode] 37. Sudoku Solver


Description

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
    Empty cells are indicated by the character ‘.’.
  4. [leetcode] 37. Sudoku Solver_i++

  5. A sudoku puzzle…
  6. [leetcode] 37. Sudoku Solver_i++_02

  7. Note:
  • The given board contain only digits 1-9 and the character ‘.’.
  • You may assume that the given Sudoku puzzle will have a single unique solution.
  • The given board size is always 9x9.

分析

题目的意思是:求解数独。

  • 思路很直接,一个深度优先搜索的问题。是一个hard类型的题目,所以比一般的dfs类型的题目要难,数组是一个矩阵,所以要双重循环遍历所有的位置,在每个位置填写数字后,要判断这个数字是否符合题目要求的三个限制。

代码

class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
solve(board);
}
bool solve(vector<vector<char>>& board){
int n=board.size();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='.'){
for(char c='1';c<='9';c++){
if(isValid(board,i,j,c)){
board[i][j]=c;
if(solve(board)){
return true;
}else{
board[i][j]='.';
}
}
}
return false;
}
}
}
return true;
}
bool isValid(vector<vector<char>>& board,int row,int col,char num){
int n=board.size();
for(int i=0;i<n;i++){
if(board[i][col]==num||board[row][i]==num){
return false;
}
if(board[3*(row/3)+i/3][3*(col/3)+i%3]==num){
return false;
}
}
return true;
}
};

参考文献

​​[编程题]sudoku-solver​​


举报

相关推荐

0 条评论