跳到正文

题解

题解:P14326 [JOI2022 预选赛 R2] 地毯 / Carpet

see_htdls约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年10月28日
收录
2025年12月12日
更新
2026年11月12日
篇幅
约 2 分钟
题目
P14326

版本

  1. v2当前
  2. v1

题目传送门

题目大意过于简单,这里不在累赘。

思路

一道十分简单的广度优先搜索( BFS )题。几乎是模板,改一下加入队列条件即可。具体代码过程见注释。

AC code

C++
#include<bits/stdc++.h>
using namespace std;
const int N = 505;
char M[N][N];//保存地图
bool vis[N][N];//这个点是否走过
int dx[4] = {1 , -1 , 0 , 0};
int dy[4] = {0 , 0 , 1 , -1};//四个方向
int step[N][N];//到每个点需要的最少步数
struct node{
	int x , y;
};
int n , m;
queue<node> q;
void bfs(int x , int y){
	vis[x][y] = 1;
	q.push({x , y});
	while(!q.empty()){//注意:函数empty()在空的时候才会返回1
		int tx = q.front().x;
		int ty = q.front().y;//别弄反了
		for(int i = 0;i < 4;i ++){//一次枚举每个方向
			int nx = tx + dx[i];
			int ny = ty + dy[i];//向该方向移动后所在位置
			if(vis[nx][ny] == 0 && nx > 0 && nx <= n && ny > 0 && ny <= m && ((M[tx][ty] == '.' && M[nx][ny] == '#') || (M[tx][ty] == '#' && M[nx][ny] == '.'))){//是否走过这个点/位置是否合法
				vis[nx][ny] = 1;
				step[nx][ny] = step[tx][ty] + 1;//步数+1
				q.push({nx , ny});//加入
			}
		}
		q.pop();//这个点已经枚举了,弹出
	}
}
signed main(){
	cin >> n >> m;
	for(int i = 1;i <= n;i ++){//输入
		for(int j = 1;j <= m;j ++){
			cin >> M[i][j];
		}
	}
	bfs(1 , 1);//从纵1横1开始
	if(vis[n][m] == 0){//如果没有被遍历到
		cout << -1;//则没有路径能到达,输出-1
		return 0;
	}
	cout << step[n][m];//输出到达n,m最少步数
	return 0;
}
原文