[LeetCode] 37. Sudoku Solver

Sudoku Solver

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 digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
  4. Empty cells are indicated by the character ‘.’.

解析

给定一个9*9的表格,求解数独。用回溯的深度优先搜索算法,重点在于从左往右搜索,遇到行末就跳到下一行。先给出DFS的模板伪代码

/**
 * DFS核心伪代码
 * 前置条件是visit数组全部设置成false
 * @param n 当前开始搜索的节点
 * @param d 当前到达的深度
 * @return 是否有解
 */
bool DFS(Node n, int d){
	if (isEnd(n, d)){//一旦搜索深度到达一个结束状态,就返回true
		return true;
	}
 
	for (Node nextNode in n){//遍历n相邻的节点nextNode
		if (!visit[nextNode]){//
			visit[nextNode] = true;//在下一步搜索中,nextNode不能再次出现
			if (DFS(nextNode, d+1)){//如果搜索出有解
				//做些其他事情,例如记录结果深度等
				return true;
			}
 
			//重新设置成false,因为它有可能出现在下一次搜索的别的路径中
			visit[nextNode] = false;
		}
	}
	return false;//本次搜索无解
}

本题代码

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        Sudoku(board, 0, 0);
    }
    
    bool Sudoku(vector<vector<char>>& board, int i, int j){
        if(i==9) return true;
        if(j==9) return Sudoku(board, i+1, 0);
        if(board[i][j] == '.'){
            for(int k=0; k<9; k++){
                if(check(board, i, j, k+'1')){
                    board[i][j] = k+'1';
                    if(Sudoku(board, i,j+1))
                        return true;
                    board[i][j] = '.';
                }
            }
        }
        else
            return Sudoku(board,i,j+1);
        return false;
    }
    bool check(vector<vector<char>>& board, int i, int j, char ch){
        for(int row=0;row<9;row++)
            if(board[row][j] == ch)
                return false;
        for(int col=0;col<9;col++)
            if(board[i][col] == ch)
                return false;
        for(int row=(i/3)*3; row<(i/3)*3+3; row++)
            for(int col = (j/3)*3; col < (j/3)*3+3; col++)
                if(board[row][col] == ch)
                    return false;
        return true;
    }
};

参考

https://leetcode.com/problems/sudoku-solver/discuss/15853/Simple-and-Clean-Solution-C%2B%2B

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值