LeetCode每日一题: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.

问题分析

和上一题不同,不仅要判断数独是否合法,还必须给出一种解法,采用dfs算法即可。

代码实现

public void solveSudoku(char[][] board) {
        if (board == null || board.length != 9 || board[0].length != 9)
            return;
        sudokuHelper(board, 0, 0);
    }

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

    private boolean isValid(char[][] board, int i, int j) {
        for (int k = 0; k < 9; k++) {
            if (k != j && board[i][k] == board[i][j])
                return false;
        }
        for (int k = 0; k < 9; k++) {
            if (k != i && board[k][j] == board[i][j])
                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 ((row != i || col != j) && board[row][col] == board[i][j])
                    return false;
            }
        }
        return true;
    }

你可能感兴趣的:(LeetCode每日一题:sudoku solver)