1.四位密码也就相当于四维坐标迷宫
2.给出的危险密码也就是障碍物
3.该坐标系有范围,大小是0~9
4.开辟多余的维度存储步数
6.定义所有坐标是否走过的状态vid列表
5.注意灵活运用
s=''.join(list(map(str, new[:4]))) 将整型列表转换为字符串
sl=list(s)将字符串转换为列表
end=list(map(int, sl)) 将列表的元素类型转换成整型
6.注意特殊情况,只要初始位置0000出现在危险密码中就不可能完成,返回-1
7.如果不是从break返回,而是while中断返回的就是未能到达密码,定义条件参数p然后判断是否返回-1或是步长news[4](这里注意不是new[4])
8.对news进行拷贝,在不影响news的情况下对new进行修改(一般的=只是映射关系,地址都一样,一变都变)
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
start = [0, 0, 0, 0, 0]
end = list(map(int, list(target)))
vid = [[[[0] * 10 for i in range(10)] for j in range(10)] for k in range(10)]
if '0000' in deadends:
return -1
def bfs(s, end):
q = deque()
q.append(s)
vid[s[0]][s[1]][s[2]][s[3]] = 1
p=0
while q:
news = q.popleft()
if news[0] == end[0] and news[1] == end[1] and news[2] == end[2] and news[3] == end[3]:
p=1
break
for i in range(4):
new = []
for j in news:
new.append(j)
new[i] += 1
if new[i] == 10:
new[i] = 0
if ''.join(list(map(str, new[:4]))) not in deadends and vid[new[0]][new[1]][new[2]][new[3]] != 1:
vid[new[0]][new[1]][new[2]][new[3]] = 1
new[4] += 1
q.append(new)
#print(new)
for i in range(4):
new = []
for j in news:
new.append(j)
new[i] -= 1
if new[i] == -1:
new[i] = 9
if ''.join(list(map(str, new[:4]))) not in deadends and vid[new[0]][new[1]][new[2]][new[3]] != 1:
vid[new[0]][new[1]][new[2]][new[3]] = 1
new[4] += 1
q.append(new)
#print(new)
if p==1:
return news[4]
return -1
return bfs(start, end)
密码锁,可相邻旋转的(左右密码可交换位置)
from queue import Queue
q=Queue()
qs=list(map(int,input()))
zd=list(map(int,input()))
vis=[[[[0]*10 for i in range(10)] for j in range(10)] for k in range(10)]
def bfs(qs,zd):
qs.append(0)
q.put(qs)
vis[qs[0]][qs[1]][qs[2]][qs[3]]=1
while(q.empty()==False):
now=q.get()
if now[0]==zd[0] and now[1]==zd[1] and now[2]==zd[2] and now[3]==zd[3]:
print(now[4])
return #出口
for i in range(4): #-1
next=now.copy()
next[i]-=1
if next[i]==0:
next[i]=9
if vis[next[0]][next[1]][next[2]][next[3]] != 1:
vis[next[0]][next[1]][next[2]][next[3]] = 1
next[4]+=1
q.put(next)
#print(next)
for i in range(4): #+1
next=now.copy()
next[i]+=1
if next[i]==10:
next[i]=1
if vis[next[0]][next[1]][next[2]][next[3]]!=1:
vis[next[0]][next[1]][next[2]][next[3]] = 1
next[4]+=1
q.put(next)
#print(next)
for i in range(3): #交换
next = now.copy()
a=next[i]
next[i]=next[i+1]
next[i+1] = a
if vis[next[0]][next[1]][next[2]][next[3]] != 1:
vis[next[0]][next[1]][next[2]][next[3]] = 1
next[4]+=1
q.put(next)
#print(next)
return -1
bfs(qs,zd)