Sudoku Solver

来源:互联网 发布:怎么制作apk软件 编辑:程序博客网 时间:2024/05/29 09:30

Sudoku Solver

 Total Accepted: 10909 Total Submissions: 52377My Submissions

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.



public class Solution {    public void solveSudoku(char[][] board) {        solve(board);    }    public boolean solve(char[][] board) {        for (int i = 0; i < 9; i++) {            for (int j = 0; j < 9; j++) {                //不要漏掉 下面的if 判断,否则wrong answer                if (board[i][j] != '.') {                    continue;                }                if (board[i][j] == '.') {                    for (int value = 1; value <= 9; value++) {                        board[i][j] = (char)(value + '0');                        if (isValid(board, i, j) && solve(board)) {                                return true;                        }                        board[i][j] = '.';                    }                }                return false;                }            }                return true;    }    boolean isValid(char[][] board, int row, int col) {        //check row        for (int i = 0; i < 9; i++) {            if (i == col) {                continue;            }             if (board[row][i] == board[row][col]) {                return false;            }        }                //check col        for (int i = 0; i < 9; i++) {           if (i == row) {                continue;            }             if (board[i][col] == board[row][col]) {                return false;            }        }                //check block        int startRow = (row / 3) * 3;        int startCol = (col / 3) * 3;        for (int i = 0; i < 3; i++) {            for (int j = 0; j < 3; j++) {                if (startRow + i == row && startCol + j == col) {                    continue;                }                if (board[startRow + i][startCol + j] == board[row][col]) {                    return false;                }            }        }        return true;    }}



0 0