leetcode解题方案--037-- 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.

分析

回溯法,挨个试
不用考虑时间复杂度。这种解放人类大脑的题基本都需要计算机累一点。
写了一个不忍直视的递归。
应该会有简化的方法。

class Solution {
     public static void solveSudoku(char[][] board) {

        if (board[0][0] != '.') {
            testAdd(board, 0, 0);
        } else {
            char init = '1';
            while (init <= '9') {
                board[0][0] = init;
                if (testAdd(board, 0, 0)) {
                    break;
                } else {
                    init++;
                }
            }
        }


        for (int i = 0; i < 9; i++) {
            System.out.println(Arrays.toString(board[i]));
        }
    }

    public static boolean testAdd(char[][] board, int x, int y) {

        //验证xy位置的正确性
        char cur = board[x][y];
        for (int i = 0; i < 9; i++) {
            if (board[i][y] == cur && i != x) {
                return false;
            }
            if (board[x][i] == cur && i != y) {
                return false;
            }
        }
        int xblock = x / 3;
        int yblock = y / 3;
        for (int i = xblock * 3; i < xblock * 3 + 3; i++) {
            for (int j = yblock * 3; j < yblock * 3 + 3; j++) {
                if (board[i][j] == cur && ((i != x) || (j != y))) {
                    return false;
                }
            }
        }
        int newx = -1, newy = -1;
        for (int i = x; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] == '.') {
                    newx = i;
                    newy = j;
                    break;
                }
            }
            if (newx != -1) {
                break;
            }
        }

        if (newx == -1 && newy == -1) {
            return true;
        }
        char testchar = '0';
        do {
            testchar++;
            board[newx][newy] = testchar;
            if (testAdd(board, newx, newy) == true) {
                return true;
            }
        } while (testchar < '9');
        board[newx][newy] = '.';
        return false;
    }
}







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值