【面試題12】矩陣中的路徑

在這裏插入圖片描述
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

考點

  • 考查對回溯法的理解,通常在二維矩陣上找路徑的問題都能用回溯法解決;
  • 考查對數組的編程能力。一般將矩陣看做二維數組。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章