头像
菜鸟12322
发布于 2021-04-20 21:26
+ 关注

c++ bfs

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct node {
	int x, y;
	int w;
};
queue<node>q;
int e[6][6];
int main()
{
	int next[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
	int x_0, y_0;
	for (int i = 1; i <= 5; i++)
	{
		for (int j = 1; j <= 5; j++)
		{
			scanf("%d", &e[i][j]);
			if (e[i][j] == 1)
			{
				x_0 = i;
				y_0 = j;
			}
		}
	}

	q.push({ x_0,y_0,0 });
	while (q.size())
	{
		struct node t = q.front();
		q.pop();
		
		for (int i = 0; i < 4; i++)
		{
			int tx = t.x + next[i][0];
			int ty = t.y + next[i][1];

			if (tx > 5 || ty > 5 || tx < 1 || ty < 1) continue;
			if (tx == 3 && ty == 3)
			{
				cout << t.w + 1 << endl;
				return 0;
			}
			q.push({ tx,ty,t.w + 1 });
		}
	}
	return 0;
}

全部评论

(0) 回帖
加载中...
话题 回帖

本文相关内容

等你来战

查看全部

热门推荐