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

Sudoku Solver

时间:2014-10-10 15:52:10      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   java   for   sp   

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.

答案

public class Solution {
        public static class IntPair
    {
        int row;

        int col;

        IntPair(int row, int col)
        {
            this.row = row;
            this.col = col;
        }
    }

    List<IntPair> list;

    char[][] board;

    public boolean solve(int index)
    {
        if (index >= list.size())
        {
            return true;
        }
        int row = list.get(index).row;
        int col = list.get(index).col;
        Set<Character> p = new HashSet<Character>(20);
        for (char i = '1'; i <= '9'; i++ )
        {
            p.add(i);
        }
        for (int i = 0; i < 9; i++ )
        {
            if (board[i][col] != '.')
            {
                p.remove(board[i][col]);
            }
            if (board[row][i] != '.')
            {
                p.remove(board[row][i]);
            }
        }
        for (int i = 0; i < 3; i++ )
        {
            for (int j = 0; j < 3; j++ )
            {
                if (board[row / 3*3 + i][col / 3*3 + j] != '.')
                {
                    p.remove(board[row / 3*3 + i][col / 3*3 + j]);
                }
            }
        }
        for (char c : p)
        {
            board[row][col] = c;
            if (solve(index + 1))
            {
                return true;
            }

        }
        board[row][col] = '.';
        return false;
    }

    public void solveSudoku(char[][] board)
    {
        int row;
        int col;
        list = new LinkedList<IntPair>();
        this.board = board;
        for (row = 0; row < 9; row++ )
        {
            for (col = 0; col < 9; col++ )
            {
                if (board[row][col] == '.')
                {
                    list.add(new IntPair(row, col));
                }
            }
        }
        solve(0);
    }
}


Sudoku Solver

标签:style   blog   http   color   io   ar   java   for   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39960901

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