zoukankan      html  css  js  c++  java
  • *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;
        }
        
        
    }
  • 相关阅读:
    COGS 14. [网络流24题] 搭配飞行员
    洛谷 P3376 【模板】网络最大流
    洛谷 P2936 [USACO09JAN]全流Total Flow
    codevs 2038 香甜的黄油 USACO
    codevs 1993 草地排水 USACO
    Openjudge 2.5 6264:走出迷宫
    洛谷 P1744 采购特价商品
    HDU
    中国剩余定理
    bzoj2157: 旅游
  • 原文地址:https://www.cnblogs.com/hygeia/p/5648382.html
Copyright © 2011-2022 走看看