码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]题解(python):037-Sudoku Solver

时间:2015-12-13 15:21:08      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:


题目来源


https://leetcode.com/problems/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.


题意分析


Input:a unsolved Sudoku

Output: a solved Sudoku

Conditions:满足数独条件,只需要找到一个答案


题目思路

用dfs的思路,对每一个空进行1-9的选择,如果不满足则回溯;满足条件为isValid(),就是满足该行,该列以及该小九方格没有使用过两个一样的元素(即数字)


AC代码(Python)


 1 class Solution(object):
 2     def solveSudoku(self, board):
 3         """
 4         :type board: List[List[str]]
 5         :rtype: void Do not return anything, modify board in-place instead.
 6         """
 7         def isValid(x, y):
 8             temp = board[x][y]
 9             board[x][y] = r
10             for i in range(9):
11                 if board[i][y] == temp:
12                     return False
13             for i in range(9):
14                 if board[x][i] == temp:
15                     return False
16             for i in range(3):
17                 for j in range(3):
18                     if board[x / 3 * 3 + i][y / 3 * 3 + j] == temp:
19                         return False
20             board[x][y] = temp
21             return True
22 
23         def dfs(board):
24             for i in range(9):
25                 for j in range(9):
26                     if board[i][j] == .:
27                         for k in 123456789:
28                             board[i][j] = k
29                             if isValid(i,j) and dfs(board):
30                                 return True
31                             board[i][j] = .
32                         return False
33             return True
34             
35         dfs(board)
36         

 

[LeetCode]题解(python):037-Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5042804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!