Golang | Leetcode Golang题解之第37题解数独

 题目:

题解:

func solveSudoku(board [][]byte) {
    var line, column [9][9]bool
    var block [3][3][9]bool
    var spaces [][2]int

    for i, row := range board {
        for j, b := range row {
            if b == '.' {
                spaces = append(spaces, [2]int{i, j})
            } else {
                digit := b - '1'
                line[i][digit] = true
                column[j][digit] = true
                block[i/3][j/3][digit] = true
            }
        }
    }

    var dfs func(int) bool
    dfs = func(pos int) bool {
        if pos == len(spaces) {
            return true
        }
        i, j := spaces[pos][0], spaces[pos][1]
        for digit := byte(0); digit < 9; digit++ {
            if !line[i][digit] && !column[j][digit] && !block[i/3][j/3][digit] {
                line[i][digit] = true
                column[j][digit] = true
                block[i/3][j/3][digit] = true
                board[i][j] = digit + '1'
                if dfs(pos + 1) {
                    return true
                }
                line[i][digit] = false
                column[j][digit] = false
                block[i/3][j/3][digit] = false
            }
        }
        return false
    }
    dfs(0)
}

相关推荐

  1. 游戏(c++题解)

    2024-04-20 19:38:06       17 阅读
  2. [力扣题解]37. 解数

    2024-04-20 19:38:06       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-20 19:38:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-20 19:38:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-20 19:38:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-20 19:38:06       18 阅读

热门阅读

  1. c语言算法之深度优先搜索(n皇后问题)

    2024-04-20 19:38:06       14 阅读
  2. Docker(十):Redis三主三从(扩容、缩容)

    2024-04-20 19:38:06       14 阅读
  3. springboot+axios传参问题

    2024-04-20 19:38:06       13 阅读
  4. Linux命令学习—linux 网络基础与网络服务管理

    2024-04-20 19:38:06       15 阅读
  5. 爱心代码咯----还缺女朋友吗?

    2024-04-20 19:38:06       13 阅读
  6. MyBatis 面试题(八)

    2024-04-20 19:38:06       13 阅读
  7. Python机器学习项目开发实战:可视化数据

    2024-04-20 19:38:06       12 阅读