矩阵中的路径
(不懂)
回溯是递归的返回判断
回溯法的“原理”:从某一个点出发,像走迷宫那样,往上下左右尝试走走看,如果符合条件可以走就走下去,直到找到符合题意的路径;如果遇到了走不通的情况,那么就调头回去继续尝试。如果到最后所有的地方都尝试过了,那么就说明找不到符合题意的路径了。
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, board, row, col, word):
self.col, self.row = col, row
board = [list(board[col * i:col * i + col]) for i in range(row)]
for i in range(row):
for j in range(col):
if board[i][j] == word[0]:
self.b = False
self.search(board, word[1:], [(i, j)], i, j)
if self.b:
return True
return False
def search(self, board, word, dict, i, j):
if word == "":
self.b = True
return
if j != 0 and (i, j - 1) not in dict and board[i][j - 1] == word[0]:
self.search(board, word[1:], dict + [(i, j - 1)], i, j - 1)
if i != 0 and (i - 1, j) not in dict and board[i - 1][j] == word[0]:
self.search(board, word[1:], dict + [(i - 1, j)], i - 1, j)
if j != self.col - 1 and (i, j + 1) not in dict and board[i][j + 1] == word[0]:
self.search(board, word[1:], dict + [(i, j + 1)], i, j + 1)
if i != self.row - 1 and (i + 1, j) not in dict and board[i + 1][j] == word[0]:
self.search(board, word[1:], dict + [(i + 1, j)], i + 1, j)