leetcode day4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
剑指offer
12 矩阵中的路径
题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。
[[“a”,“b”,“c”,“e”],
[“s”,“f”,“c”,“s”],
[“a”,“d”,“e”,“e”]]
但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
我的思路:我搞的老复杂了,也是DFS,但不是递归
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
class Node():
def __init__(self,x,y):
self.x=x
self.y=y
self.count=0
self.father=None
def findFather(self,x,y):
node=self
while(node!=None):
if node.x==x and node.y==y:
return True
node=node.father
return False
length=len(word)
stack=[]
if length==0:
return False
if len(board)==0:
return False
if len(board[0])==0:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==word[0]:
node=Node(i,j)
stack.append(node)
while(len(stack)>0):
node=stack.pop()
x=node.x
y=node.y
count=node.count
if count==length-1:
return True
if x>0 and board[x-1][y]==word[count+1] and node.findFather(x-1,y)==False:
if count+1==length-1:
return True
newnode=Node(x-1,y)
newnode.count=count+1
newnode.father=node
stack.append(newnode)
if x<len(board)-1 and board[x+1][y]==word[count+1]and node.findFather(x+1,y)==False:
if count+1==length-1:
return True
newnode=Node(x+1,y)
newnode.count=count+1
newnode.father=node
stack.append(newnode)
if y>0 and board[x][y-1]==word[count+1]and node.findFather(x,y-1)==False:
if count+1==length-1:
return True
newnode=Node(x,y-1)
newnode.count=count+1
newnode.father=node
stack.append(newnode)
if y<len(board[0])-1and board[x][y+1]==word[count+1]and node.findFather(x,y+1)==False:
if count+1==length-1:
return True
newnode=Node(x,y+1)
newnode.count=count+1
newnode.father=node
stack.append(newnode)
return False
其他思路:DFS递归
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(i, j, k):
if not 0 <= i < len(board) or not 0 <= j < len(board[0]) or board[i][j] != word[k]: return False
if k == len(word) - 1: return True
board[i][j] = ''
res = dfs(i + 1, j, k + 1) or dfs(i - 1, j, k + 1) or dfs(i, j + 1, k + 1) or dfs(i, j - 1, k + 1)
board[i][j] = word[k]
return res
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(i, j, 0): return True
return False
作者:jyd
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。