Sudoku Solver

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.

思路:

  常见的回溯模板

我的代码:

public class Solution {

    public void solveSudoku(char[][] board) {

        if(board == null || board.length == 0 || board[0].length == 0)  return;

        placeSudoku(board);

    }

    public boolean placeSudoku(char[][] board)

    {

        for(int i = 0; i < 9; i++)

        {

            for(int j = 0; j < 9; j++)

            {

                if(board[i][j] == '.')

                {

                    for(char k = '1'; k <= '9'; k++)

                    {

                        if(canPut(board, i, j, k))

                        {

                            board[i][j] = k;

                            if(placeSudoku(board))

                                return true;

                            board[i][j] = '.';

                        }

                    }

                    return false;

                }

            }

        }

        return true;

    }

    public boolean canPut(char[][] board, int i, int j, char c) {

        for(int k = 0; k < 9; k++)

        {

            if((board[i][k] == c && k != j) || (board[k][j] == c && k != i))    return false;

        }

        //test box

        int boxRow = i/3;

        int boxCol = j/3;

        for(int m = boxRow * 3; m < boxRow * 3 + 3; m++)

        {

            for(int n = boxCol * 3; n < boxCol * 3 + 3; n++)

            {

                if(board[m][n] == '.' || (m == i && n == j))  continue;

                else

                {

                    if(board[m][n] == c)    return false;

                }

            }

        }

        return true;

    }

}
View Code

学习之处:

  • 还是使用之前总结的回溯模板,就是return true和return false地方稍微换了一下。
  • 第一遍刷Sudoku Solver 四次通过,这次竟然>4次,汗颜。。。越来手速越不给力了,实验室写代码果然不适合集中精力啊。

你可能感兴趣的:(sudo)