洛谷P1141 01迷宫

P1141 01迷宫

题目链接-P1141 01迷宫
在这里插入图片描述
在这里插入图片描述
解题思路
dfs求连通块+记忆化,如果不记忆化会TLE

  • 每一次搜索会找到一个区块,该区块中所有点的答案都相同,所以答案可以用数组 f[N][N]记录
  • 对于题目要求查询的每一个点先判断是否前面搜索时已经得到答案,如果是则存入ans[]数组中,以便最后输出,如果不是则进行dfs深搜
  • 其他都跟dfs的板子一样,不再做讲解,具体操作见代码

附上代码

#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
using namespace std;
const int INF=0x3f3f3f3f;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
const double PI=acos(-1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e6+5;
typedef long long ll;
typedef pair<int,int> PII;
int n,m,f[1010][1010],ans[N];
char mp[1010][1010];
void dfs(int x,int y,char c,int it){
	if(x<1||y<1||x>n||y>n||f[x][y]!=-1)
		return ;
	f[x][y]=it;
	ans[it]++;
	for(int i=0;i<4;i++){
		int dx=x+dir[i][0];
		int dy=y+dir[i][1];
		if(mp[dx][dy]!=c)
			dfs(dx,dy,mp[dx][dy],it);
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		cin>>mp[i]+1;
	memset(f,-1,sizeof f);
	for(int i=0;i<m;i++){
		int x,y;
		cin>>x>>y;
		if(f[x][y]!=-1)
			ans[i]=ans[f[x][y]];
		else
			dfs(x,y,mp[x][y],i);
	}
	for(int i=0;i<m;i++)
		cout<<ans[i]<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
洛谷p1238是一个题目,具体要求是给定一个迷宫,求从起点到终点的最短路径。这个问题可以使用链表来表示迷宫,并使用广度优先搜索算法来求解最短路径。 以下是一个示例代码,演示了如何使用链表和广度优先搜索算法来解决洛谷p1238题目中的迷宫问题: ```python from collections import deque # 定义迷宫的链表节点类 class Node: def __init__(self, x, y, val): self.x = x self.y = y self.val = val self.next = None # 构建迷宫的链表 def build_maze(maze): m = len(maze) n = len(maze[0]) head = Node(0, 0, maze[0][0]) curr = head for i in range(m): for j in range(n): if i == 0 and j == 0: continue node = Node(i, j, maze[i][j]) curr.next = node curr = node return head # 广度优先搜索算法求解最短路径 def bfs(maze): m = len(maze) n = len(maze[0]) visited = [[False] * n for _ in range(m)] queue = deque([(0, 0, 0)]) # (x, y, step) visited[0][0] = True while queue: x, y, step = queue.popleft() if x == m - 1 and y == n - 1: return step for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: nx, ny = x + dx, y + dy if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny] and maze[nx][ny] == 0: queue.append((nx, ny, step + 1)) visited[nx][ny] = True return -1 # 示例迷宫 maze = [ [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] ] # 构建迷宫的链表 maze_head = build_maze(maze) # 使用广度优先搜索算法求解最短路径 shortest_path = bfs(maze) print("最短路径长度为:", shortest_path) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值