37. Sudoku Solver

来源:互联网 发布:ubuntu如何添加中文 编辑:程序博客网 时间:2024/06/15 15:51

思路就是很直接,一个个试,不行就回溯,按照flow来,如果1到9都不行就return false


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 {    public void solveSudoku(char[][] board) {        if(board == null)return ;                solve(board);    }        // need to know whether it is solvable, so create another function    public boolean solve(char[][] board) {    for(int i=0; i<board.length; i++) {        for(int j=0; j<board[0].length; j++) {        if(board[i][j] == '.') {        for(char k='1'; k<='9'; k++) {        if(isValid(board, i, j, k)) {        board[i][j] = k;// trial        if(solve(board))return true;        elseboard[i][j]='.';//backtrack         }        }        return false;// just follow the flow        }        }        }    return true;    }private boolean isValid(char[][] board, int i, int j, char k) {for(int p=0; p<board[0].length; p++)if(board[i][p] == k)return false;for(int p=0; p<board.length; p++)if(board[p][j] == k)return false;int start_row = i / 3 * 3, start_col = j / 3 * 3;for(int m=0; m<3; m++)for(int n=0; n<3; n++)if(board[start_row+m][start_col+n] == k)return false;return true;}}


0 0
原创粉丝点击