第2章 面试需要的基础知识
面试题4:二维数组中的查找
面试题5:替换空格
面试题6:从尾到头打印链表
面试题7:重建二叉树
面试题9:用两个栈实现队列
面试题10:斐波那契数列
面试题11:旋转数组的最小值
面试题12:矩阵中的路径
面试题15:二进制数中1的个数
第3章 高质量的代码
第4章 解决面试题的思路
第5章 优化时间和空间效率
第6章 面试中的各项能力
第7章 两个面试案例
题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
做这道题要崩溃了!!!,给的不是矩阵是个字符串!!!递归没递归出来!!!各种小错误bug!!!
解题思路
- 先找到矩阵中与第一个字符相同的点;
- 从该点开始深度优先搜索。
实战
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
def dfs(x, y, path):
if not path:
return True
index = x * cols + y
if x < 0 or x >= rows or y < 0 or y >= cols or visited[index]:
return False
if matrix[index] != path[0]:
return False
visited[index] = 1
if (dfs(x-1, y, path[1:]) or
dfs(x, y+1, path[1:]) or
dfs(x, y-1, path[1:]) or
dfs(x+1, y, path[1:])):
return True
visited[index] = 0
return False
for i in range(rows):
for j in range(cols):
if matrix[i*cols+j] == path[0]:
visited = [0] * rows * cols
exist = dfs(i, j, path)
if exist: return True
return False
静下心来做,好像也不用很久。。。回溯过程和上面稍有不同
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix or not path:
return False
def recc(string, point):
if not string:
return True
px, py = point[0], point[1]
for d in direction:
x, y = px + d[0], py + d[1]
index = y*cols + x
if index < 0 or index >= rows * cols or visited[index]:
continue
visited[index] = True
if string[0] == matrix[index]:
flag = recc(string[1:], (x, y))
if flag:
return True
visited[index] = False
return False
direction = [(-1, 0), (0, 1), (1, 0), (0, -1)]
for row in range(rows):
for col in range(cols):
if matrix[row*cols + col] == path[0]:
visited = [False] * rows * cols
visited[row*cols + col] = True
flag = recc(path[1:], (col, row))
if flag:
return True
return False