zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):037-Sudoku Solver


    题目来源


    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         
  • 相关阅读:
    Node实践之二
    Node实践之一
    总结的JS数据类型判定(非常全面)
    利用chorme调试手机网页
    设计模式总结综述
    Python3标准库使用样例
    systemd 文档教程
    编写Postgres扩展之五:代码组织和版本控制
    编写Postgres扩展之三:调试
    编写Postgres扩展之四:测试
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5042804.html
Copyright © 2011-2022 走看看