Leetcode

LeetCode代码分析——37. Sudoku Solver(

2018-05-14  本文已影响0人  JackpotDC

题目描述

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.
    1-9每行必须出现且只能出现一次
  2. Each of the digits 1-9 must occur exactly once in each column.
    1-9每列必须出现且只能出现一次
  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
    每个3*3的子格子内(粗框标记的),1-9必须出现且只能出现一次
    Empty cells are indicated by the character '.'.
A sudoku puzzle... ...and its solution numbers marked in red.

Note:

思路分析

其实没啥更好的解法,就是DFS深度优先搜索找结果,

代码实现

总之就是一个DFS搜索,注意下1,2,3条件的判断,然后想清楚什么时候递归(当前填数没问题,要确认下面层次的问题)以及递归的出口(当前位置1-9都遍历完还是没有合适的就返回false,如果9*9的格子全遍历完了中间没有返回false就说明数组中没有'.'了,填满了)就行了。

public class Solution {

    /**
     * 6 / 6 test cases passed.
     *  Status: Accepted
     *  Runtime: 17 ms
     *
     * @param board
     */
    public void solveSudoku(char[][] board) {
        solve(board);
    }

    private boolean solve(char[][] board) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] == '.') {
                    for (int k = 0; k < 9; k++) {
                        board[i][j] = (char) ('1' + k);
                        if (isValid(board, i, j) && solve(board)) {
                            return true;
                        } else {
                            // backtracking to '.'
                            board[i][j] = '.';
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }

    private boolean isValid(char[][] board, int x, int y) {
        for (int i = 0; i < board.length; i++) {
            if (board[i][y] == board[x][y] || board[x][i] == board[x][y]) {
                return false;
            }
        }

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                int pos_x = x - x % 3 + i;
                int pos_y = y - y % 3 + j;
                if (x != pos_x && y != pos_y && board[x][y] == board[pos_x][pos_y]) {
                    return false;
                }
            }
        }

        return true;

    }
}
上一篇 下一篇

猜你喜欢

热点阅读