• *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.

    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;
        }
        
        
    }
  • 相关阅读:
    配置缓存过期时间
    浏览器读取缓存流程
    nginx做代理的优化
    系统优化
    每日总结2.2
    每日总结2.1
    《构建之法》阅读笔记三
    每日总结1.29
    每日总结1.28
    每日总结1.27
  • 原文地址:https://www.cnblogs.com/hygeia/p/5648382.html
Copyright © 2020-2023  润新知