洛谷 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;
}
相关推荐
如竟没有火炬5 分钟前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
寂静山林18 分钟前
UVa 12526 Cellphone Typing
算法
czy87874751 小时前
用C语言实现原型模式
c语言·原型模式
czy87874751 小时前
用C语言实现原型模式时,如何确定需要深拷贝还是浅拷贝?
c语言·原型模式
kyle~1 小时前
C++---嵌套类型(Nested Types)封装与泛型的基石
开发语言·c++·算法
sali-tec1 小时前
C# 基于halcon的视觉工作流-章48-短路断路
开发语言·图像处理·人工智能·算法·计算机视觉
墨染点香2 小时前
LeetCode 刷题【128. 最长连续序列】
算法·leetcode·职场和发展
被AI抢饭碗的人2 小时前
算法题(240):最大食物链计数
算法
熬了夜的程序员2 小时前
【LeetCode】82. 删除排序链表中的重复元素 II
数据结构·算法·leetcode·链表·职场和发展·矩阵·深度优先
欧克小奥2 小时前
Floyd判圈算法(Floyd Cycle Detection Algorithm)
算法·floyd