寒假训练POJ-3984题解

问题链接:POJ-3984

思路

广度优先搜索后,再从终点出发,找出最短的路径记录下来,最后输出。

AC的代码

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int main()
{
	char a[5][6]; int a1[5][5] = { 0 }; queue<int> k; int yidong[4][2] = { {0,1},{0,-1},{1,0},{-1,0} }; vector<int> note;
	for (int i = 0; i < 5; i++)
		for (int j = 0; j < 5; j++)
			cin >> a[i][j];
	k.push(0);
	k.push(0);
	while (k.size())
	{
		int x, y;
		x = k.front();
		k.pop();
		y = k.front();
		k.pop();
		for (int i = 0; i < 4; i++)
		{
			int x1, y1;
			x1 = x + yidong[i][0];
			y1 = y + yidong[i][1];
			if (x1 >= 0 && x1 < 5 && y1 >= 0 && y1 < 5 && a[x1][y1] == '0'&&a1[x1][y1] == 0)
			{
				k.push(x1);
				k.push(y1);
				a1[x1][y1] = a1[x][y] + 1;
			}
		}
	}
	int x2 = 4, y2 = 4;
	for (int i = 0; i < a1[4][4]-1; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			int x3, y3;
			x3 = x2 + yidong[j][0];
			y3 = y2 + yidong[j][1];
			if (x3 >= 0 && x3 < 5 && y3 >= 0 && y3 < 5 && a1[x3][y3] == a1[x2][y2] - 1)
			{
				note.push_back(x3);
				note.push_back(y3);
				x2 = x3;
				y2 = y3;
				break;
			}
		}
	}
	cout << "(0, 0)" << endl;
	for (int i = note.size()-1; i > 0; i = i - 2)
		cout << "(" << note[i - 1] << ", " << note[i] << ")" << endl;
	cout << "(4, 4)" << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43970556/article/details/86676101