LeetCode 37. Sudoku Solver(数读游戏)

本文介绍两种使用深度优先搜索解决数独的方法。方法一通过简单的深度优先搜索递归填充空格;方法二则通过评估每个空格的不确定性来优化搜索过程。

原题网址:https://leetcode.com/problems/sudoku-solver/

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.

方法一:深度优先搜索。

public class Solution {
    private boolean[][] rows, cols;
    private boolean[][][] subs;
    private boolean find(char[][] board, int cell) {
        if (cell == 81) return true;
        int row = cell / 9;
        int col = cell % 9;
        int subr = row / 3;
        int subc = col / 3;
        if (board[row][col] != '.') return find(board, cell+1);
        for(int i=0; i<9; i++) {
            if (rows[row][i] || cols[col][i] || subs[subr][subc][i]) continue;
            rows[row][i] = true;
            cols[col][i] = true;
            subs[subr][subc][i] = true;
            board[row][col] = (char)('1' + i);
            if (find(board, cell+1)) return true;
            rows[row][i] = false;
            cols[col][i] = false;
            subs[subr][subc][i] = false;
        }
        board[row][col] = '.';
        return false;
    }
    public void solveSudoku(char[][] board) {
        rows = new boolean[9][9];
        cols = new boolean[9][9];
        subs = new boolean[3][3][9];
        for(int row = 0; row < 9; row ++) {
            for(int col = 0; col < 9; col ++) {
                if (board[row][col] == '.') continue;
                int num = board[row][col]-'1';
                rows[row][num] = true;
                cols[col][num] = true;
                int subr = row / 3;
                int subc = col / 3;
                subs[subr][subc][num] = true;
            }
        }
        find(board, 0);
    }
}

方法二:优先处理确定性高的格子,即剪枝,但比较繁琐。

public class Solution {
    private Cell[] cells;
    private int maxDepth = 0;
    private int[] rowSolved, colSolved;
    private int[][] subSolved;
    private boolean[][] rows, cols;
    private boolean[][][] subs;
    private boolean find(char[][] board, int depth) {
        if (depth == cells.length) return true;
        if (depth == maxDepth+1) {
            int priority = depth;
            for(int i=depth+1; i<cells.length; i++) {
                if (cells[i].uncertainty < cells[priority].uncertainty) priority = i;
            }
            Cell temp = cells[depth];
            cells[depth] = cells[priority];
            cells[priority] = temp;
            maxDepth = depth;
        }
        int row = cells[depth].row;
        int col = cells[depth].col;
        int subr = row / 3;
        int subc = col / 3;
        for(int i=0; i<9; i++) {
            if (rows[row][i] || cols[col][i] || subs[subr][subc][i]) continue;
            rows[row][i] = true;
            cols[col][i] = true;
            subs[subr][subc][i] = true;
            board[row][col] = (char)('1' + i);
            rowSolved[row] ++;
            colSolved[col] ++;
            subSolved[subr][subc] ++;
            if (find(board, depth+1)) return true;
            rows[row][i] = false;
            cols[col][i] = false;
            subs[subr][subc][i] = false;
            rowSolved[row] --;
            colSolved[col] --;
            subSolved[subr][subc] --;
        }
        board[row][col] = '.';
        return false;
    }

    public void solveSudoku(char[][] board) {
        rowSolved = new int[9];
        colSolved = new int[9];
        subSolved = new int[3][3];
        rows = new boolean[9][9];
        cols = new boolean[9][9];
        subs = new boolean[3][3][9];
        int unsolved = 0;
        for(int row = 0; row < 9; row ++) {
            for(int col = 0; col < 9; col ++) {
                if (board[row][col] == '.') {
                    unsolved ++;
                } else {
                    int num = board[row][col]-'1';
                    rows[row][num] = true;
                    cols[col][num] = true;
                    int subr = row / 3;
                    int subc = col / 3;
                    subs[subr][subc][num] = true;
                    rowSolved[row] ++;
                    colSolved[col] ++;
                    subSolved[subr][subc] ++;
                }
            }
        }
        cells = new Cell[unsolved];
        int cpos = 0;
        int priority = -1;
        for(int row = 0; row < 9; row ++) {
            for(int col = 0; col < 9; col ++) {
                if (board[row][col] == '.') {
                    int subr = row / 3;
                    int subc = col / 3;
                    Cell cell = new Cell(row, col, 27-rowSolved[row]-colSolved[col]-subSolved[subr][subc]);
                    if (priority < 0 || cell.uncertainty < cells[priority].uncertainty) priority = cpos;
                    cells[cpos++] = cell;
                }
            }
        }
        Cell temp = cells[0];
        cells[0] = cells[priority];
        cells[priority] = temp;
        find(board, 0);
    }
}
class Cell {
    int row, col;
    int uncertainty;
    Cell(int row, int col, int uncertainty) {
        this.row = row;
        this.col = col;
        this.uncertainty = uncertainty;
    }
}


### 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?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值