洛谷 P1746 离开中山路 C语言 bfs

题目:

https://www.luogu.com.cn/problem/P1746

bfs模型,注意下输入是字符,也要创建个字符数组。

代码如下:

复制代码
#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0}; 
struct Node{
	int x;
	int y;
	int step;
};
bool stl[1005][1005];
char map[1005][1005];//0 表示马路,1 表示店铺,注意两个数之间没有空格
int n; 
int x1,y1,x2,y2;
int main() 
{
	cin >> n;
	for(int i = 1 ; i <= n ; i++)
	{
		for(int j = 1 ; j <= n ; j++)
		{
		  cin >> map[i][j];
		}
	}
	cin >> x1 >> y1 >> x2 >> y2;

	queue <Node> q;//创建队列 
	Node start = {x1,y1,0};//直接创建队首对象start 
	q.push(start);
	stl[x1][y1] = true;
	while(!q.empty())
	{
		int x = q.front().x;//取出队首的x,y 
		int y = q.front().y;
		int step = q.front().step;
		if(x == x2 && y == y2)
		{
			cout <<step;
			break;
		}
		for(int k = 0 ; k < 4 ; k++)
		{
			int tx = x + dx[k];
			int ty = y + dy[k];
			if(tx >= 1 && tx <= n && ty >= 1 && ty <= n && stl[tx][ty] == false && map[tx][ty] == '0')
			{
				stl[tx][ty] = true;//标记已探索 
				Node newpos;
				newpos.x = tx;
				newpos.y = ty;
				newpos.step = step + 1;
				q.push(newpos); 
			}
		}
		q.pop();
	 } 
	return 0;
}
相关推荐
Escalating_xu14 分钟前
【C 语言】深入理解指针(2):数组名、数组传参、二级指针与指针数组
java·c语言·开发语言
Allen_LVyingbo34 分钟前
信息化部门在AI时代的编程转移路径分析(上)
人工智能·python·算法·健康医疗·数据库开发·时序数据库·数据库架构
七牛云行业应用39 分钟前
Jev 报 401 / api_key_required 怎么解决:TypeSafe AI 官方错误码表与排查步骤
算法·github
晴天的雨.9921 小时前
【C++算法】三数之和
开发语言·c++·算法
心中有你02142 小时前
C语言实现文件异或加密与RLE压缩算法
c语言·开发语言
阿钱真强道2 小时前
18 嵌入式操作系统 | uloop 定时器:周期任务与网络上报
c语言·定时器·周期任务·uloop
多多爱学习2 小时前
括号有几层?得看还有多少个左括号没闭合
c语言·c++·算法·面试
续写烂尾2 小时前
MK SD NAND(贴片式TF卡)替代Nor Flash:1Gb容量与256Mb Nor
算法·microsoft
AI+程序员在路上2 小时前
AP6275S蓝牙双接口解析:HCI UART与PCM的分工与协同
linux·c语言·物联网
jingli92 小时前
本地向量库索引把 C 盘塞爆 48.6G:一次 LanceDB 膨胀排查与根治实录
c语言·开发语言