博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode]Word Search @ Python
阅读量:7036 次
发布时间:2019-06-28

本文共 1234 字,大约阅读时间需要 4 分钟。

原题地址:https://oj.leetcode.com/problems/word-search/

题意:

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,

Given board =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]

word = "ABCCED", -> returns true,

word = "SEE", -> returns true,
word = "ABCB", -> returns false.

解题思路:使用dfs来搜索,为了避免已经用到的字母被重复搜索,将已经用到的字母临时替换为'#'就可以了。不知道用bfs可行否。

代码:

class Solution:    # @param board, a list of lists of 1 length string    # @param word, a string    # @return a boolean    def exist(self, board, word):        def dfs(x, y, word):            if len(word)==0: return True            #up            if x>0 and board[x-1][y]==word[0]:                tmp=board[x][y]; board[x][y]='#'                if dfs(x-1,y,word[1:]):                    return True                board[x][y]=tmp            #down            if x
0 and board[x][y-1]==word[0]: tmp=board[x][y]; board[x][y]='#' if dfs(x,y-1,word[1:]): return True board[x][y]=tmp #right if y

 

转载地址:http://thjal.baihongyu.com/

你可能感兴趣的文章
Android常用网址
查看>>
sbt解析spark依赖报错
查看>>
Hibernate的SQL执行顺序引发的血案
查看>>
eclipse远程连接Hbase数据库
查看>>
Freemarker不显示对象的属性的原因
查看>>
Timsort工作原理
查看>>
MySQL性能调优与架构设计--MySql逻辑模块组成
查看>>
Command模式
查看>>
python的nltk中文使用和学习资料汇总帮你入门提高
查看>>
Input TableViewCell
查看>>
Passcode
查看>>
iTellAFriend
查看>>
BlockAlertsAnd-ActionSheets
查看>>
MKMovingBlockAnimation
查看>>
TapKu Graph
查看>>
XCode's one very useful cmd:po
查看>>
面试需要的基础知识-合并排序数组
查看>>
关于Unity 2018的实体组件系统(ECS)一
查看>>
安卓系统下安装完apk程序后,具体的文件夹位置在哪里呢
查看>>
Echarts---添加渐变功能
查看>>