Posts Tagged 【math】Sudoku Solver

Sudoku Solver

  Total Accepted: 26308  Total Submissions: 121888 My Submissions

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.

/*
http://www.csie.ntnu.edu.tw/~u91029/Backtracking.html#1
回溯法&&DFS==【退回,已经操作的状态复原】
所有解void
void sovle(char[][] board, int x, int y) {
    if(y == 9) {y = 0; x++;}
    if(x == 9) {solution(); return;}
    //do thing
}
有一解boolean
boolean sovle(char[][] board)
boolean sovle(cahr[][] board,int x,int y)
*/
public class Solution {
    public void solveSudoku(char[][] board) {
        sovle(board);
    }
    
 private boolean sovle(char[][] board) {  
        for(int i = 0;i<9;i++)  
            for(int j = 0;j<9;j++) {  
                if(board[i][j] == '.') {  
                    for(char k = '1';k<='9';k++) {  
                        board[i][j] = k;  
                        if(isVaild(board,i,j) && sovle(board)) {  
                            return true;  
                        }  
                    }  
                    board[i][j] = '.';  
                    return false;  
                }  
            }  
        return true;  
    }  
    
    private boolean isVaild(char[][] board,int i,int j) {
        int[] row = new int[9];
        int[] column = new int[9];
        int[] block = new int[9];
        int a = i/3*3;
        int b = j/3*3;
        for(int k = 0;k<9;k++) {
            if(board[i][k] != '.') {
                if(row[board[i][k]-'1']>0) return false;
                else {
                    row[board[i][k]-'1']++;
                }
            }
            if(board[k][j] != '.') {
                if(column[board[k][j]-'1']>0) return false;
                else {
                    column[board[k][j]-'1']++;
                }
            }
        }
        for(int k1 = 0;k1<3;k1++)
            for(int k2 = 0;k2<3;k2++) {
                if(board[a+k1][b+k2] != '.') {
                    if(block[board[a+k1][b+k2]-'1']>0) return false;
                    else {
                        block[board[a+k1][b+k2]-'1']++;
                    }
                }
            }
        return true;
    }
}





Have you met this question in a real interview? 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值