求助bfs
  • 板块P1443 马的遍历
  • 楼主baking
  • 当前回复0
  • 已保存回复0
  • 发布时间2022/3/22 20:06
  • 上次更新2023/10/28 05:55:41
查看原帖
求助bfs
405268
baking楼主2022/3/22 20:06
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;

int n, m;
int xto[8] = { 1,2,2,1,-1,-2,-2,-1 };//上右开始
int yto[8] = { 2,1,-1,-2,-2,-1,1,2 };
struct node
{
	int x;
	int y;
	int step = 0;
}ini;

int final[410][410] = {-1};

int main()
{
	cin >> n >> m;
	cin >> ini.x >> ini.y;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (final[i][j] == -1)
			{
				bool flag[410][410] = { 0 };
				queue<node> q;
				q.push(ini);
				node temp;
				while (!q.empty())
				{
					temp = q.front();
					q.pop();
					if (temp.x == i && temp.y == j)
					{
						break;
					}
					for (int k = 0; k < 8; k++)
					{
						if (temp.x + xto[k] <= n && temp.x + xto[k] >= 1 && temp.y + yto[k] <= m && temp.y + yto[k] >= 1 && !flag[temp.x + xto[k]][temp.y + yto[k]])
						{
							q.push(node{ temp.x + xto[k],temp.y + yto[k],temp.step + 1 });
							flag[temp.x + xto[k]][temp.y + yto[k]] = 1;
							if (final[temp.x + xto[k]][temp.y + yto[k]] ==-1)
							{
								final[temp.x + xto[k]][temp.y + yto[k]] = temp.step + 1;
							}
						}
					}
				}
				if (temp.x == i && temp.y == j)
				{
					final[i][j] = temp.step;
				}
			}
			
		}
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			printf("%-5d", final[i][j]);
		}
		printf("\n");
	}
}

样例都过不了,哭了

2022/3/22 20:06
加载中...