洛谷 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;
}
相关推荐
[J] 一坚28 分钟前
深入浅出理解冒泡、插入排序和归并、快速排序递归调用过程
c语言·数据结构·算法·排序算法
czlczl2002092537 分钟前
算法:二叉搜索树的最近公共祖先
算法
司铭鸿37 分钟前
祖先关系的数学重构:从家谱到算法的思维跃迁
开发语言·数据结构·人工智能·算法·重构·c#·哈希算法
SoleMotive.2 小时前
redis实现漏桶算法--https://blog.csdn.net/m0_74908430/article/details/155076710
redis·算法·junit
-森屿安年-2 小时前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
北京地铁1号线2 小时前
数据结构:堆
java·数据结构·算法
散峰而望2 小时前
C++数组(一)(算法竞赛)
c语言·开发语言·c++·算法·github
自然常数e2 小时前
深入理解指针(1)
c语言·算法·visual studio
WWZZ20253 小时前
快速上手大模型:深度学习13(文本预处理、语言模型、RNN、GRU、LSTM、seq2seq)
人工智能·深度学习·算法·语言模型·自然语言处理·大模型·具身智能
Christo33 小时前
AAAI-2024《Multi-Class Support Vector Machine with Maximizing Minimum Margin》
人工智能·算法·机器学习·支持向量机·数据挖掘