#37 Sudoku Solver

Description

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ‘.’.

在这里插入图片描述
在这里插入图片描述

Note:

  • The given board contain only digits 1-9 and the character ‘.’.
  • You may assume that the given Sudoku puzzle will have a single unique solution.
  • The given board size is always 9x9.

解题思路

哎呀这不是我觉得36不用进行很开心的解数独嘛?!

该来的总会来

至少对得起他这个hard

对没错就是对bfs不够熟练

对着一个void想了半天该怎么递归……(是傻子了

还是要用Boolean来递归吧……不然怎么知道这个点影响的后续有没有成功匹配呢

最后查了半天发现错在对九宫格的判断上……直接用 x / 3 作为开始……觉得自己当时没睡醒orz

class Solution {
    public static Boolean check(int x, int y, char[][]board){
        int i, j;
        Set<Character> col, row, block;
        col = new HashSet<>();
        row = new HashSet<>();
        block = new HashSet<>();
        for(i = 1; i < 10; i++){
            col.add(String.valueOf(i).charAt(0));
            row.add(String.valueOf(i).charAt(0));
            block.add(String.valueOf(i).charAt(0));
        }
        for(i = 0; i < 9; i++){
            if(col.contains(board[x][i]))
                col.remove(board[x][i]);
            else if(board[x][i] != '.')
                return false;
            if(row.contains(board[i][y]))
                row.remove(board[i][y]);
            else if(board[i][y] != '.')
                return false;
        }
        for(i = x / 3 * 3; i < x / 3 * 3 + 3; i++){
            for(j = y / 3 * 3; j < y / 3 * 3 + 3; j++){
                if(block.contains(board[i][j]))
                    block.remove(board[i][j]);
                else if(board[i][j] != '.')
                    return false;
            }
        }
        return true;
    }
    public void solveSudoku(char[][] board){
        solve(board);
    }
    public Boolean solve(char[][] board) {
        int i, j, k;
        for(i = 0; i < 9; i++){
            for(j = 0; j < 9; j++){
                if(board[i][j] == '.'){
                    for(k = 1; k < 10; k++){
                        board[i][j] = String.valueOf(k).charAt(0);
                        if(check(i, j, board) && solve(board))
                            return true;
                        else{
                            board[i][j] = '.';
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }
}

照例摸了下通过里面1ms的大佬代码

看到位运算就知道自己还要继续努力Orz

希望有朝一日自己也能写出位运算的代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值