DFS
1.排列数字
dfs和递归差不多,具体图示如下图:
![(蓝桥杯)DFS+BFS算法题目-python_第1张图片](http://img.e-com-net.com/image/info8/e0e18c723bb94fec83e7bde62d0de49c.jpg)
![(蓝桥杯)DFS+BFS算法题目-python_第2张图片](http://img.e-com-net.com/image/info8/b8b50d00a50e4a23a5f1dbd18e8182f3.jpg)
N=10
path=[0]*N
state=[False]*N
def dfs(u):
if u==n:
for i in range(n):
print(path[i],end=' ')
print()
for i in range(n):
if state[i]==False:
path[u]=i+1
state[i]=True
dfs(u+1)
path[u]=0
state[i]=False
n=int(input())
dfs(0)
2.n皇后问题
![(蓝桥杯)DFS+BFS算法题目-python_第3张图片](http://img.e-com-net.com/image/info8/aad97146c40f4157b02acfa7f74a78ca.jpg)
![(蓝桥杯)DFS+BFS算法题目-python_第4张图片](http://img.e-com-net.com/image/info8/1fffed39571f404c82f94fae41917819.jpg)
.Q..
...Q
Q...
..Q.
..Q.
Q...
...Q
.Q..
def dfs(x,y,queue):
if y==n:
x,y=x+1,0
if x==n:
if queue==n:
for i in range(n):
for j in range(n):
print(chessboard[i][j],end='')
print()
print()
return
if not row[x] and not col[y] and not dg[x+y] and not udg[y-x+n]:
chessboard[x][y]='Q'
row[x],col[y],dg[x+y],udg[y-x+n]=1,1,1,1
dfs(x,y+1,queue+1)
row[x],col[y],dg[x+y],udg[y-x+n],chessboard[x][y]=0,0,0,0,'.'
dfs(x,y+1,queue)
if __name__=='__main__':
N=10
n=int(input())
chessboard=[['.' for _ in range(N)] for _ in range(N)]
row,col,dg,udg=[0]*N,[0]*N,[0]*2*N,[0]*2*N
dfs(0,0,0)
BFS
走迷宫
![(蓝桥杯)DFS+BFS算法题目-python_第5张图片](http://img.e-com-net.com/image/info8/88d60fce6de946f0b4227aea8daf6c53.jpg)
输入样例:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出样例:
8
def bfs():
dx=[-1,0,1,0]
dy=[0,1,0,-1]
queue=[(0,0)]
trace[0][0]=0
while queue:
x,y=queue.pop(0)
if (x,y)==(n-1,m-1):
return trace[x][y]
for i in range(4):
a=x+dx[i]
b=y+dy[i]
if 0<=a<n and 0<=b<m and graph[a][b]!=1 and trace[a][b]==-1:
queue.append((a,b))
trace[a][b]=trace[x][y]+1
N=101
n,m=map(int,input().split())
graph=[[0]*N for _ in range(N)]
trace=[[-1]*N for _ in range(N)]
for i in range(n):
graph[i][0:m]=list(map(int,input().split()))
print(bfs())
![(蓝桥杯)DFS+BFS算法题目-python_第6张图片](http://img.e-com-net.com/image/info8/18a55b27d5784c14be468ca3d98178b6.jpg)
青蛙跳杯子
![(蓝桥杯)DFS+BFS算法题目-python_第7张图片](http://img.e-com-net.com/image/info8/d6502072043349d9a4afcc34661c5cec.jpg)
x=input()
y=input()
move=[1,-1,2,-2,3,-3]
aset={x}
def bfs():
Q=[(x,0)]
while Q:
old=Q.pop(0)
for i in move:
a=list(old[0])
b=old[1]
c=a.index('*')
d=c+i
if 0<=d<len(x):
a[c]=a[d]
a[d]='*'
e=''.join(a)
b+=1
if e==y:
print(b)
return
if e not in aset:
aset.add(e)
Q.append((e,b))
bfs()