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

*Sudoku Solver

时间:2016-07-06 23:32:14      阅读:356      评论:0      收藏:0      [点我收藏+]

标签:

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) {
        sudokuHelper(board);
    }
    
    public boolean sudokuHelper(char[][] board)
    {
        for(int i=0;i<9;i++)
        {
            for(int j=0;j<9;j++)
            {
                if(board[i][j]!=‘.‘)continue;
                
                for(int k=1;k<=9;k++)
                {
                    board[i][j]=(char) (k+‘0‘);
                    if(isValid(board,i,j) && sudokuHelper(board))
                    {
                        return true;
                    }
                    board[i][j]=‘.‘;
                }
                return false;
            }
        }
        return true;
    }
    
    public boolean isValid(char[][] board, int a, int b)
    {
        Set<Character> set = new HashSet<Character>();
        //row
        for(int i=0;i<9;i++)
        {
            if(set.contains(board[a][i])) return false;
            if(board[a][i]>‘0‘&&board[a][i]<=‘9‘)
            {
                set.add(board[a][i]);    
            }
        }
        
        //col
        set = new HashSet<Character>();
        for(int i=0;i<9;i++)
        {
            if(set.contains(board[i][b])) return false;
            if(board[i][b]>‘0‘&&board[i][b]<=‘9‘)
            {
                set.add(board[i][b]);    
            }
            
        }
        
        //box
        set = new HashSet<Character>();
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                int x = a/3*3+i;
                int y = b%3*3+j;
                if(set.contains(board[x][y])) return false;
                if(board[x][y]>‘0‘&&board[x][y]<=‘9‘)
                {
                    set.add(board[x][y]);    
                }
            }
        }
        
        return true;
    }
    
    
}

 

*Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5648382.html

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