洛谷 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;
}
相关推荐
No0d1es17 分钟前
电子学会青少年软件编程(C/C++)1级等级考试真题试卷(2025年9月)
java·c语言·c++·青少年编程·电子学会·真题·一级
小O的算法实验室32 分钟前
2025年TRE SCI1区TOP,随机环境下无人机应急医疗接送与配送的先进混合方法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
小白程序员成长日记1 小时前
2025.11.06 力扣每日一题
算法·leetcode
暴风鱼划水1 小时前
算法题(Python)数组篇 | 4.长度最小的子数组
python·算法·力扣
gugugu.1 小时前
算法:二分算法类型题目总结---(含二分模版)
算法
大G的笔记本1 小时前
算法篇常见面试题清单
java·算法·排序算法
小龙报1 小时前
《算法通关指南数据结构和算法篇(4)--- 队列和queue》
c语言·开发语言·数据结构·c++·创业创新·学习方法·visual studio
7澄12 小时前
深入解析 LeetCode 数组经典问题:删除每行中的最大值与找出峰值
java·开发语言·算法·leetcode·intellij idea
AI科技星2 小时前
宇宙的几何诗篇:当空间本身成为运动的主角
数据结构·人工智能·经验分享·算法·计算机视觉
前端小L2 小时前
二分查找专题(二):lower_bound 的首秀——精解「搜索插入位置」
数据结构·算法