Python題解
class Solution:
def hasPath(self, matrix, rows, cols, path):
seek = [False]*(cols*rows)
def helper(seek, m, rows, cols, row, col, pidx, path):
if pidx == len(path):
return True
hasPath = False
if row >= 0 and row < rows and col >= 0 and col < cols and m[row*cols+col]==path[pidx] and not seek[row*cols+col]:
seek[row*cols+col] = True
hasPath = helper(seek, m, rows, cols, row, col-1, pidx+1, path) or \
helper(seek, m, rows, cols, row, col+1, pidx+1, path) or \
helper(seek, m, rows, cols, row-1, col, pidx+1, path) or \
helper(seek, m, rows, cols, row+1, col, pidx+1, path)
if not hasPath:
seek[row*cols+col] = False
return hasPath
for i in range(rows):
for j in range(cols):
if helper(seek, matrix, rows, cols, i, j, 0, path):
return True
return False
考點
- 考查對回溯法的理解,通常在二維矩陣上找路徑的問題都能用回溯法解決;
- 考查對數組的編程能力。一般將矩陣看做二維數組。