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         
  • 相关阅读:
    故障-因为MAC地址冲突造成的故障
    MySQL安全审计(init_connect)
    GLIBC升级
    HTTPS优化与证书
    封装打包Python脚本
    fiddler进行弱网测试的坑
    Jmeter的安装
    win10安装Mysql
    linux常用命令(五)
    linux常用命令(四)
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5042804.html
Copyright © 2011-2022 走看看