zoukankan      html  css  js  c++  java
  • 79. 单词搜索-回溯算法(leetcode)

    给定一个二维网格和一个单词,找出该单词是否存在于网格中。

    单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

     想法:本题跟我们9021 quiz7-8的类型是一样的,9024也用C写过一次,都是在二维数组里搜索,用回溯算法,今天脑袋有点不清醒,以后多刷几次。

    学到的点:

      1. 每一步递归中,都要注意判断 start_x,start_y的取值范围

      2. 学到了python里面的语法还可以直接大于小于判断。   

        if 0<=start_x<noOfRow and 0<=start_y<noOfCol

    class Solution:
        def exist(self, board: List[List[str]], word: str) -> bool:
            
            noOfRow = len(board)
            noOfCol = len(board[0])
            visited = [[False for _ in range(noOfCol)] for _ in range(noOfRow)]
            for i in range(noOfRow):
                for j in range(noOfCol):
                    if self.helper(i,j,board,visited,noOfRow,noOfCol,0,word):
                        print(i,j)
                        return True
            return False

        def helper(self,start_x,start_y,board,visited,noOfRow,noOfCol,point,word):
            directions = [(0,1),(1,0),(0,-1),(-1,0)]
            if point == len(word)-1:
                if 0<=start_x<noOfRow and 0<=start_y<noOfCol and board[start_x][start_y] == word[point] and not visited[start_x][start_y]:
                    return True
                else: 
                    return False
            if 0<=start_x<noOfRow 
                and 0<=start_y<noOfCol and board[start_x][start_y] == word[point] and point<len(word) and not visited[start_x][start_y]:
                visited[start_x][start_y] = True
                for direction in directions:
                    new_x = start_x + direction[0]
                    new_y = start_y + direction[1]
                    if self.helper(new_x,new_y,board,visited,noOfRow,noOfCol,point+1,word):
                        return True
                visited[start_x][start_y] = False
            return False
  • 相关阅读:
    Selenium常用API的使用java语言之7-控制浏览器操作
    Selenium常用API的使用java语言之6-WebDriver常用方法
    Selenium常用API的使用java语言之5-selenium元素定位
    Selenium常用API的使用java语言之4-环境安装之Selenium
    Selenium常用API的使用java语言之3-selenium3 浏览器驱动
    Selenium常用API的使用java语言之2-环境安装之IntelliJ IDEA
    ES6常用七大特性
    css实现类似朋友圈九宫格缩略图完美展示
    NodeJS入门篇
    viewport其实没那么难理解
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12442026.html
Copyright © 2011-2022 走看看