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

[leetcode] Sudoku Solver

时间:2014-06-27 12:50:48      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

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.

bubuko.com,布布扣

A sudoku puzzle...

bubuko.com,布布扣

...and its solution numbers marked in red.

https://oj.leetcode.com/problems/sudoku-solver/

思路:类似于N-Queens的回溯方案,对于每个空格,依次填入每个数字,如果合法,继续下去,直至填满。

注意:此时isValid只需比较当前填入的值所在区域的合法性!

 

/**
 * http://blog.csdn.net/zxzxy1988/article/details/8586289
 * http://blog.csdn.net/linhuanmars/article/details/20748761
 * @author Dong Jiang
 *
 */
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 (board[i][j] == ‘.‘) {
                    for (int k = 1; k <= 9; k++) {
                        board[i][j] = (char) (‘0‘ + k);

                        if (isValid(board, i, j) && solve(board))
                            return true;

                        board[i][j] = ‘.‘;
                    }
                    return false;
                }
            }
        }
        return true;

    }

    private boolean isValid(char[][] board, int x, int y) {
        int i, j;
        for (i = 0; i < 9; i++)
            if (i != x && board[i][y] == board[x][y])
                return false;

        for (j = 0; j < 9; j++)
            if (j != y && board[x][j] == board[x][y])
                return false;

        for (i = 3 * (x / 3); i < 3 * (x / 3 + 1); i++)
            for (j = 3 * (y / 3); j < 3 * (y / 3 + 1); j++)
                if (i != x && j != y && board[i][j] == board[x][y])
                    return false;

        return true;
    }

    public static void main(String[] args) {
        char[][] board = { { ‘5‘, ‘3‘, ‘.‘, ‘.‘, ‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘ },
                { ‘6‘, ‘.‘, ‘.‘, ‘1‘, ‘9‘, ‘5‘, ‘.‘, ‘.‘, ‘.‘ }, { ‘.‘, ‘9‘, ‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘ },
                { ‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘3‘ }, { ‘4‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘3‘, ‘.‘, ‘.‘, ‘1‘ },
                { ‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘ }, { ‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘8‘, ‘.‘ },
                { ‘.‘, ‘.‘, ‘.‘, ‘4‘, ‘1‘, ‘9‘, ‘.‘, ‘.‘, ‘5‘ }, { ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘.‘, ‘7‘, ‘9‘ } };

        new Solution().solveSudoku(board);

    }
}

参考

http://blog.csdn.net/linhuanmars/article/details/20748761

http://blog.csdn.net/zxzxy1988/article/details/8586289

 

[leetcode] Sudoku Solver,布布扣,bubuko.com

[leetcode] Sudoku Solver

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810741.html

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