面试题12:矩阵中的路径
题目描述:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
详细代码:
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix or rows < 0 or cols < 0 or not path:
return False
path_index = 0
markmatrix = [0] * (rows * cols)
for row in range(rows):
for col in range(cols):
if self.hasPathCore(matrix, rows, cols, row, col, path, path_index, markmatrix):
return True
return False
def hasPathCore(self, matrix, rows, cols, row, col, path, path_index, markmatrix):
if path_index == len(path):
return True
haspath = False
if row >= 0 and row < rows and col >= 0 and col < cols and matrix[row * cols + col] == path[path_index] and nor markmatrix[row * cols +col]:
path_index += 1
markmatrix[row * cols + col] = True
haspath = self.hasPathCore(matrix, rows, cols, row+1, col, path, path_index, markmatrix) or \
self.hasPathCore(matrix, rows, cols, row-1, col, path, path_index, markmatrix) or \
self.hasPathCore(matrix, rows, cols, row, col+1, path, path_index, markmatrix) or \
self.hasPathCore(matrix, rows, cols, row, col-1, path, path_index, markmatrix)
if not haspath:
path_index -= 1
markmatrix[row * cols + col] = False
return haspath
面试题13:
题目描述:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
详细代码:
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
if threshold < 0 or rows < 1 or cols < 1:
return 0
markmatrix = [0] * (rows * cols)
count = self.movingCountCore(threshold, rows, cols, 0, 0, markmatrix)
return count
def movingCountCore(self, threshold, rows, cols, row, col, markmatrix):
value = 0
if self.check(threshold, rows, cols, row, col, markmatrix):
markmatrix[row * cols +col] = True
value = 1+ self.movingCountCore(threshold, rows, cols, row + 1, col, markmatrix) + \
self.movingCountCore(threshold, rows, cols, row - 1, col, markmatrix) + \
self.movingCountCore(threshold, rows, cols, row, col + 1, markmatrix) + \
self.movingCountCore(threshold, rows, cols, row, col - 1, markmatrix)
return value
def check(self, threshold, rows, cols, row, col, markmatrix):
if row >= 0 and row < rows and col >= 0 and col < cols and self.getDigitNum(row) + self.getDigitNum(col) == threshold and not markmatrix[row *cols +col]:
return True
return False
def getDigitNum(self, number):
sum = 0
while number > 0:
sum += number % 10
number = number // 10
return sum