bfs模板
from collections import deque
def bfs(a,b,c,d):
'''a,b: 起点 c,d: 终点 '''
dis = [[0]*m for _ in range(n)]
queue = deque()
#1、将起点塞入到队列中,打上标记
queue.append([a,b])
dis[a][b] = 0
#2、当队列非空
while len(queue) != 0:
# 2.1 取出队首元素u
x,y = queue.popleft()
#2.2 判断u是否为终点
if x == c and y == d:
return dis[x][y]
#2.3 将u相连的所有点v,只要v未标记,则入队列
for delta_x,delta_y in [(1,0),(0,1),(-1,0),(0,-1)]:
xx ,yy= x+delta_x,y+delta_y
#特判:未越界、未标记、非障碍
if 0<=xx<n and 0<=yy<m and dis[xx][yy] == -1 and Map[xx][yy]!='x':
queue.append([xx,yy])
dis[xx][yy] = dis[x][y] + 1
return -1
n,m = map(int,input().split())
Map = [input() for _ in range(n)]
a,b,c,d = map(int,input().split())
a,b,c,d = a-1,b-1,c-1,d-1
print(bfs(a,b,c,d))
dfs深度优先搜索
将x分成n个正整数,要求后一个大于等于前一个
def dfs(depth,last_value):
# depth : 表示当前处于第depth层
if depth == n :
if sum(path) != x:
return
print(path)
return
for i in range(last_value,x + 1):
path[depth] = i
dfs(depth + 1,i)
x = int(input())
n = int(input())
path = [0]*n #表示第i个数字
dfs(0,1)
dfs 4494 黄金树
def dfs(depth): # depth: 第几个节点
if son[depth][0] != -1: #处理左儿子
gold[son[depth][0]] = gold[depth] + 1
dfs(son[depth][0])
if son[depth][1] != -1: #处理右儿子
gold[son[depth][1]] = gold[depth] - 1
dfs(son[depth][1])
n = int(input())
w = [0]+list(map(int, input().split()))
son = [[0,0]]
for _ in range(1,n+1):
tmp = list(map(int, input().split()))
son.append(tmp)
gold = [0] * (n+1)
ans = 0
dfs(1)
for i in range(1,n+1):
if gold[i] == 0:
ans += w[i]
print(ans)
print(gold)
dfs 回溯排列数 4360
def dfs(depth):
'''
:param depth: 从第depth次操作开始
'''
if depth == n:
print(path)
return
#全排列k
for j in range(1,n+1):
if vis[j]:
continue
vis[j] = True
path.append(j)
dfs(depth+1)
vis[j] = False
path.pop(-1)
n = int(input())
path = [] #操作的顺序
vis = [False] * (n+1)
dfs(0)
dfs 特殊的多边形 3075
#利用DFS求所有的n边形,边长乘积不超过100000
def dfs(depth,last_value,tot,mul): #depth: 第几条边
#last_value : 上一条边长
if depth == n:
if tot > 2*path[-1]:
ans[mul] += 1
return
for i in range(last_value+1,10000):
if mul*(i**(n-depth)) <= 100000:
path.append(i)
dfs(depth+1,i,tot+i,mul*i)
path.pop()
else:
break
#ans[i] 表示价值为i的n边形的个数
ans = [0] * 100001
t,n = map(int,input().split())
path = []
dfs(0,0,0,1)
#求ans在【L,R】的区间和
for i in range(1,100001):
ans[i] += ans[i-1]
for _ in range(t):
l,r = map(int, input().split())
print(ans[r]-ans[l-1])
dfs 记忆化 216 地宫取宝
# 下标从0开始,x,y要-1
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
dir = [(1,0),(0,1)]
from functools import lru_cache
@lru_cache(maxsize=None) #记忆化搜索
def dfs(x,y,z,w):
''':param x: 当前横坐标
:param y: 当前纵坐标
:param z: 当前拿的宝物数量
:param w: 当前拿的宝物的最大价值
'''
if x==n-1 and y==m-1:
if z == k:
return 1
if z == k-1 and w<Map[x][y]:
return 1
return 0
#方案数 = 右的方案数+下的方案数
ans = 0
for i in range(2):
xx ,yy = x+dir[i][0],y+dir[i][1]
if xx < n and yy < m:
ans += dfs(xx, yy, z, w)
if w < Map[x][y]:
ans += dfs(xx,yy,z+1,Map[x][y])
ans %= 1000000007
return ans
n,m,k = map(int,input().split())
Map = []
for _ in range(n):
tmp = list(map(int,input().split()))
Map.append(tmp)
print(dfs(0,0,0,-1))