[LeetCode] 37. Sudoku Solver

本文介绍了一个使用深度优先搜索(DFS)算法解决数独问题的程序。通过递归地填充空格并验证每一步是否符合数独规则来找到解决方案。文章提供了详细的C++代码实现,并解释了如何检查行、列及子网格内的数字重复性。

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

### LeetCode Problem 37: Sudoku Solver #### Problem Description The task involves solving a partially filled Sudoku puzzle. The input is represented as a two-dimensional integer array `board` where each element can be either a digit from '1' to '9' or '.' indicating empty cells. #### Solution Approach To solve this problem, one approach uses backtracking combined with depth-first search (DFS). This method tries placing numbers between 1 and 9 into every cell that contains '.', checking whether it leads to a valid solution by ensuring no conflicts arise within rows, columns, and subgrids[^6]. ```cpp void solveSudoku(vector<vector<char>>& board) { backtrack(board); } bool backtrack(vector<vector<char>> &board){ for(int row = 0; row < 9; ++row){ for(int col = 0; col < 9; ++col){ if(board[row][col] != '.') continue; for(char num='1';num<='9';++num){ if(isValidPlacement(board,row,col,num)){ placeNumber(num,board,row,col); if(backtrack(board)) return true; removeNumber(num,board,row,col); } } return false; } } return true; } ``` In the provided code snippet: - A function named `solveSudoku()` initiates the process. - Within `backtrack()`, nested loops iterate over all positions in the grid looking for unassigned spots denoted by '.' - For any such spot found, attempts are made to insert digits ranging from '1' through '9'. - Before insertion, validation checks (`isValidPlacement`) ensure compliance with Sudoku rules regarding uniqueness per row/column/subgrid constraints. - If inserting a number results in reaching a dead end without finding a complete solution, removal occurs before trying another possibility. This algorithm continues until filling out the entire board correctly or exhausting possibilities when returning failure status upward along recursive calls stack frames. --related questions-- 1. How does constraint propagation improve efficiency while solving puzzles like Sudoku? 2. Can genetic algorithms provide alternative methods for tackling similar combinatorial problems effectively? 3. What optimizations could enhance performance further beyond basic DFS/backtracking techniques used here?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值