码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 37. Sudoku Solver —— 解数独

时间:2018-06-28 22:48:30      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:following   code   ica   git   bool   优先   col   The   rac   

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 ‘.‘.
 
技术分享图片
 
A sudoku puzzle...

 技术分享图片

 
...and its solution numbers marked in red.
 
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.

 

觉得这道题更像是一个深度优先搜索+回溯问题。深度优先搜索的部分是,每次填入一个数,只有当这个数是有效且也不会造成数独未来无效的时候,才会继续递归填入下一个数。而回溯的部分是,当填入的数是违反数独规则的,或者在将来使得数独无效,那么就要把填入的数回溯到初始状态。想明白这一点就非常好做了。

 


Java

class Solution {
    public void solveSudoku(char[][] board) {
        check(board);
    }
    
    private boolean check(char[][] board) {
        for (int i = 0; i < 9; i++) {
                for (int j = 0; j < 9; j++) {
                    if (board[i][j] == ‘.‘) {
                        for (char p = ‘1‘; p <= ‘9‘; p++) {
                            board[i][j] = p;
                            if (isValid(board, i, j) && check(board))
                                return true;
                            board[i][j] = ‘.‘;    
                        }
                        return false;
                    }
                }
        }
        return true;
    }
    
    private boolean isValid(char[][] board, int i, int j) {
        for (int p = 0; p < 9; p++) 
            if (i != p && board[i][j] == board[p][j])
                return false;
        for (int p = 0; p < 9; p++)
            if (j != p && board[i][j] == board[i][p])
                return false;
        int row = 3 * (i / 3);
        int col = 3 * (j / 3);
        for (int p = row; p < row+3; p++)
            for (int q = col; q < col+3; q++)
                if (p != i && q != j && board[i][j] == board[p][q])
                    return false;
        return true;
    }
}

 

LeetCode 37. Sudoku Solver —— 解数独

标签:following   code   ica   git   bool   优先   col   The   rac   

原文地址:https://www.cnblogs.com/tengdai/p/9240889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!