[python]leetcode(79). Word Search
来源:互联网 发布:虫虫钢琴软件 编辑:程序博客网 时间:2024/06/05 19:52
problem
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 =
[ [‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’] ]word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
solution
题目的意思就是给定一个二维的字符数组和一个字符串,只允许上下左右连接看能否形成给定的字符串(数组中每个字符只能使用一次)。
先考虑只能从某个固定位置起始的组合,如果说没有“数组中每个字符只能使用一次”的限制的话,我们只需要递归的对这个位置的四个方向探索word[1:]
即可,加上这个限制后我们每次探索前要把这个位置先修改成非字符元素(如None),但是注意因为是递归算法所以每次修改之后都要改回原来的值。
只要对数组中每个元素都调用上面的函数即可。
class Solution(object): def exist(self, board, word): def find(board, word, i, j, m, n): '''从i,j开始深度优先搜索word是否在board中 ''' if word == '': return True if i < 0 or i >= m or j < 0 or j >= n: return False elif word[0] == board[i][j]: board[i][j] = None #标记 res = find(board, word[1:], i+1, j, m, n)or find(board, word[1:], i-1, j, m, n)or find(board, word[1:], i, j+1, m, n)or find(board, word[1:], i, j-1, m, n): board[i][j] = word[0] #恢复原来的值 return res if len(word) == 0: return True m = len(board) if m == 0: return False n = len(board[0]) for i in range(m): for j in range(n): if find(board, word, i, j, m, n): return True else: return False
总结
本题考察的主要是对多维数组的深度优先搜索,如果在递归中修改了可变对象的值,在递归函数结束之后要改回来。
ps:在python中如果or运算符左边的值为True则停止往后计算,直接返回True,所以可以利用这个特性做dfs,如果有一个为真则直接返回,不用一个个判断
- [python]leetcode(79). Word Search
- 【Leetcode】【python】Word Search
- [Leetcode] 212. Word Search @python
- Leetcode 79 Word Search
- LeetCode 79: Word Search
- [leetcode 79] Word Search
- [LeetCode 79]Word Search
- leetcode || 79、Word Search
- [leetCode]79(Word Search)
- leetcode-79 Word Search
- Leetcode #79 Word Search
- Leetcode #79 Word Search
- LeetCode(79) Word Search
- leetcode 79: Word Search
- 【leetcode】【79】Word Search
- (LeetCode 79) Word Search
- LeetCode 79: Word Search
- LeetCode 79 Word Search
- BZOJ 1911 [Apio2010]特别行动队 (斜率优化DP)
- 数据结构实验之链表一:顺序建立链表
- 启动第三方的Activity,service
- WireShark如何抓取本地localhost的包
- 计算机如何执行取数指令
- [python]leetcode(79). Word Search
- hibernate错误总结
- mybatis 传递多个参数
- com.opensymphony.xwork2.config.ConfigurationException: Unable to load configuration.
- IAR for 430软件的简单使用
- QT之信号槽(一)
- 1006. 换个格式输出整数 (15)
- 百炼 3468:电池的寿命
- zookeeper注册配置与启动