码迷,mamicode.com
首页 > 其他好文 > 详细

Sudoku Solver

时间:2015-03-10 16:47:03      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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次,汗颜。。。越来手速越不给力了,实验室写代码果然不适合集中精力啊。

Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4326100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!