leetcode: 37. Sudoku Solver
来源:互联网 发布:深圳赛维网络ceo陈文平 编辑:程序博客网 时间:2024/06/06 02:21
Q
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.
Example
A sudoku puzzle…
…and its solution numbers marked in red.
AC
# Time: ((9!)^9)# Space: (1)class Solution(object): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ def solveSudoku(self, board): def isValid(board, x, y): for k in xrange(9): if (x != k and board[k][y] == board[x][y]) or (y != k and board[x][k] == board[x][y]): return False for i in xrange(3*(x/3), 3*(x/3+1)): for j in xrange(3*(y/3), 3*(y/3+1)): if (i != x or j != y) and board[i][j] == board[x][y]: return False return True def solver(board): for i in xrange(9): for j in xrange(9): if board[i][j] == '.': for k in xrange(9): board[i][j] = chr(ord('1')+k) if isValid(board, i, j) and solver(board): return True board[i][j] = '.' return False return True solver(board)if __name__ == '__main__': board = [[".",".","9","7","4","8",".",".","."], ["7",".",".",".",".",".",".",".","."], [".","2",".","1",".","9",".",".","."], [".",".","7",".",".",".","2","4","."], [".","6","4",".","1",".","5","9","."], [".","9","8",".",".",".","3",".","."], [".",".",".","8",".","3",".","2","."], [".",".",".",".",".",".",".",".","6"], [".",".",".","2","7","5","9",".","."]] Solution().solveSudoku(board) assert board == [["5","1","9","7","4","8","6","3","2"], ["7","8","3","6","5","2","4","1","9"], ["4","2","6","1","3","9","8","7","5"], ["3","5","7","9","8","6","2","4","1"], ["2","6","4","3","1","7","5","9","8"], ["1","9","8","5","2","4","3","6","7"], ["9","7","5","8","6","3","1","2","4"], ["8","3","2","4","9","1","7","5","6"], ["6","4","1","2","7","5","9","8","3"]]
阅读全文
0 0
- LeetCode --- 37. Sudoku Solver
- LeetCode 37.Sudoku Solver
- [Leetcode] 37. Sudoku Solver
- [leetcode] 37. Sudoku Solver
- Leetcode 37. Sudoku Solver
- leetcode 37. Sudoku Solver
- LeetCode 37. Sudoku Solver
- leetcode.37. Sudoku Solver
- LeetCode-37.Sudoku Solver
- leetcode 37. Sudoku Solver
- (Leetcode)37. Sudoku Solver
- [LeetCode] 37. Sudoku Solver
- leetcode 37.Sudoku Solver
- leetcode 37. Sudoku Solver
- leetcode 37. Sudoku Solver
- leetcode-37. Sudoku Solver
- [LeetCode]37. Sudoku Solver
- leetcode 37. Sudoku Solver
- 飞康CEO:一切正向积极的方向发展
- 2017-11-14 源码包安装
- vue中如何在v-for中动态的使用将index拼接字符串后绑定id属性
- 分布式锁的几种实现方式~
- JAVA-多线程-思维导图
- leetcode: 37. Sudoku Solver
- win server 2012 使用Navicat for mysql 链接不了本地的mysql数据库,提示10038 或 0
- 哇,下载前端早读课PDF啦
- Python3.x POST data的编码错误解决方法
- [数据结构]循环队列中判断队满与队空
- 菜鸡的R语言学习笔记——数据结构 Part 1
- linux下创建用户
- 关于其他博主采用代码问题予以讲解
- JAVA链式编程