洛谷 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;
}
相关推荐
spcier5 小时前
图论拓扑排序-Kahn 算法
算法·图论
知星小度S5 小时前
动态规划(一)——思想入门
算法·动态规划
ysa0510305 小时前
动态规划-逆向
c++·笔记·算法
燃于AC之乐5 小时前
我的算法修炼之路--7—— 手撕多重背包、贪心+差分,DFS,从数学建模到路径DP
c++·算法·数学建模·深度优先·动态规划(多重背包)·贪心 + 差分
闻缺陷则喜何志丹5 小时前
【BFS 动态规划】P12382 [蓝桥杯 2023 省 Python B] 树上选点|普及+
c++·蓝桥杯·动态规划·宽度优先·洛谷
海上Bruce5 小时前
C primer plus (第六版)第十二章 编程练习第3题
c语言
chinesegf5 小时前
文本嵌入模型的比较(一)
人工智能·算法·机器学习
SundayBear6 小时前
零基础入门MQTT协议
c语言·单片机
我能坚持多久6 小时前
D16—C语言内功之数据在内存中的存储
c语言·开发语言
We་ct6 小时前
LeetCode 6. Z 字形变换:两种解法深度解析与优化
前端·算法·leetcode·typescript