剑指offer题解 - 回溯

本系列为剑指offer刷题笔记,刷题平台为牛客网

本文主要是回溯相关题目题解总结。

[TOC]

65.矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串”bcced”的路径,但是矩阵中不包含”abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

解题思路

这是一个可以用回溯法解决的典型问题。

首先,遍历这个矩阵,我们很容易就能找到与字符串str中第一个字符相同的矩阵元素ch。然后遍历ch的上下左右四个字符,如果有和字符串str中下一个字符相同的,就把那个字符当作下一个字符(下一次遍历的起点),如果没有,就需要回退到上一个字符,然后重新遍历。为了避免路径重叠,需要一个辅助矩阵来记录路径情况。

下面代码中,当矩阵坐标为(row,col)的格子和路径字符串中下标为pathLength的字符一样时,从4个相邻的格子(row,col-1)、(row-1,col)、(row,col+1)以及(row+1,col)中去定位路径字符串中下标为pathLength+1的字符。

如果4个相邻的格子都没有匹配字符串中下标为pathLength+1的字符,表明当前路径字符串中下标为pathLength的字符在矩阵中的定位不正确,我们需要回到前一个字符串(pathLength-1),然后重新定位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here

if len(matrix) == 0 or rows <= 0 or cols <= 0:
return False
if len(path) == 0:
return True

visited = [False]*(rows*cols)

for i in range(rows):
for j in range(cols):
if self.HasPath(matrix, rows, cols, path, i, j, visited, 0):
return True
return False

def HasPath(self, matrix, rows, cols, path, i, j, visited, pathLen):
if pathLen == len(path):
return True
curHasPath = False
if 0 <= i < rows and 0 <= j < cols and matrix[i*cols+j] == path[pathLen] and not visited[i*cols+j]:
visited[i*cols+j] = True
pathLen += 1
curHasPath = self.HasPath(matrix, rows, cols, path, i+1, j, visited, pathLen) or self.HasPath(matrix, rows, cols, path, i-1, j, visited, pathLen) or self.HasPath(matrix, rows, cols, path, i, j+1, visited, pathLen) or self.HasPath(matrix, rows, cols, path, i, j-1, visited, pathLen)
if not curHasPath:
pathLen -= 1
visited[i*cols+j] = False
return curHasPath

66 机器人的运动范围

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

解题思路

和上一道题十分相似,只不过这次的限制条件变成了坐标位数之和。对于求坐标位数之和,我们单独用一个函数实现,然后套入上一道题的代码中即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
if rows <= 0 or cols <= 0:
return 0
visited = [False]*(rows*cols)
return self.moving(threshold, rows, cols, 0, 0, visited)

def moving(self, threshold, rows, cols, i, j, visited):
count = 0
if 0 <= i < rows and 0 <= j < cols and self.getnum(i)+self.getnum(j) <= threshold and not visited[i*cols+j]:
visited[i*cols+j] = True
count = 1 + self.moving(threshold, rows, cols, i+1, j, visited)+ \
self.moving(threshold, rows, cols, i-1, j, visited) + \
self.moving(threshold, rows, cols, i, j+1, visited) + \
self.moving(threshold, rows, cols, i, j-1, visited)
return count

def getnum(self, num):
res = 0
while num:
res += num%10
num //= 10
return res
Donate comment here
------------The End------------
0%