杭电OJ 1180(C++)

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

struct Node
{
	int t; //当前步数
	int x; //当前x坐标
	int y; //当前y坐标
};

int M, N; //行数,列数
char mp[24][24]; //地图数据
bool vis[24][24]; //访问情况
int dir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} }; //四种移动方向

//广搜
int BFS(Node temp)
{
	queue<Node> q;
	while (!q.empty())
		q.pop();
	q.push(temp);
	while (!q.empty())
	{
		temp = q.front();
		q.pop();
		if (mp[temp.x][temp.y] == 'T') //到达终点
			return temp.t;
		for (int i = 0; i < 4; i++)
		{
			Node next;
			next.x = temp.x + dir[i][0];
			next.y = temp.y + dir[i][1];
			next.t = temp.t + 1;
			if (vis[next.x][next.y] || mp[next.x][next.y] == '*' || next.x < 0 || next.y < 0 || next.x >= M || next.y >= N)
				continue;
			if (mp[next.x][next.y] == '|')
			{
				//朝原方向再走一步
				next.x += dir[i][0];
				next.y += dir[i][1];
				if (vis[next.x][next.y] || mp[next.x][next.y] == '*' || next.x < 0 || next.y < 0 || next.x >= M || next.y >= N)
					continue;
				if ((temp.t % 2 == 1 && dir[i][1] == 0) || (temp.t % 2 == 0 && dir[i][0] == 0))
					++next.t; //原地等待1秒
			}
			else if (mp[next.x][next.y] == '-')
			{
				next.x += dir[i][0];
				next.y += dir[i][1];
				if (vis[next.x][next.y] || mp[next.x][next.y] == '*' || next.x < 0 || next.y < 0 || next.x >= M || next.y >= N)
					continue;
				if ((temp.t % 2 == 1 && dir[i][0] == 0) || (temp.t % 2 == 0 && dir[i][1] == 0))
					++next.t;
			}
			vis[next.x][next.y] = true;
			q.push(next);
		}
	}
}

int main()
{
	while (cin >> M >> N)
	{
		memset(vis, false, sizeof(vis));
		Node start;
		for (int i = 0; i < M; ++i) //输入地图数据
		{
			cin.get(); //读入回车
			for (int j = 0; j < N; ++j)
			{
				cin >> mp[i][j];
				if (mp[i][j] == 'S') //起点
				{
					vis[i][j] = true;
					start.x = i;
					start.y = j;
					start.t = 0;
				}
			}
		}
		cout << BFS(start) << endl;
	}
	return 0;
}
发布了138 篇原创文章 · 获赞 1 · 访问量 7019

猜你喜欢

转载自blog.csdn.net/Intelligence1028/article/details/104569597