backtrace
题目: 给定一个二维数组,给定一个序列,找到数组中该序列的路径,例如:
数组:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
序列:
[1, 2, 3, 7, 6, 10, 11, 12]
分析:回溯法
# use list to simulate stack
# s = list()
# s.append(4)
# s.append(5)
# print(s)
# s.pop()
# print(s)
import numpy as np
def findNext(num,i,j,maxi,maxj,matrix):
if i+1<=maxi and matrix[i+1][j]==num and visit[i+1][j]==0:
visit[i+1][j]=1
return i+1,j,1
if i-1>=0 and matrix[i-1][j]==num and visit[i-1][j]==0:
visit[i-1][j]=1
return i-1,j,1
if j-1>=0 and matrix[i][j-1]==num and visit[i][j-1]==0:
visit[i][j-1]=1
return i,j-1,1
if j+1<=maxj and matrix[i][j+1]==num and visit[i][j+1]==0:
visit[i][j+1]=1
return i,j+1,1
else: # not find
return i,j,-1
visit = np.zeros((3,4))
matrix = np.array([x+1 for x in range(12)])
print(matrix)
matrix = matrix.reshape((3,4))
print(matrix)
target = [11,10,6,5]
s = []
target_index=0
start_i, start_j = -1,-1
for i in range(len(matrix)): # find the start position
flag=0
for j in range(len(matrix[0])):
if matrix[i][j]==target[target_index]:
s.append(matrix[i][j])
target_index+=1
start_i, start_j = i,j
flag=1
break
if flag==1:
break
while 1:
if len(s)==len(target):
break
now_i,now_j, flag = findNext(target[target_index],start_i,start_j,len(matrix)-1,len(matrix[0])-1,matrix)
if flag==-1: # not find
s.pop()
target_index-=1
else:
s.append(matrix[now_i][now_j])
target_index+=1
start_i,start_j = now_i,now_j
print(s)