HDU 1484(Basic wall maze)

#include <iostream>
#include <stack>
using namespace std;
const int MAXN = 10;
const int INF = 0x3f3f3f3f;

int mp[MAXN][MAXN][4]; //地图,第三个维度代表格子的四个方向是否存在墙
int dis[MAXN][MAXN]; //格子之间的最小步数
int pre[MAXN][MAXN][2]; //记录前驱
int dx[4] = { 0,-1,0,1 }, dy[4] = { 1,0,-1,0 }; //移动方向
int sx, sy, ex, ey; //起点坐标,终点坐标
int wx1, wy1, wx2, wy2; //墙的起点坐标和终点坐标

//深搜,搜索起点到其余各点的最小步数
void DFS(int x, int y, int cnt)
{
	for (int i = 0; i < 4; ++i)
	{
		if (mp[x][y][i] == 1) //遇到墙
			continue;

		int tx = x + dx[i];
		int ty = y + dy[i];
		if (tx < 1 || ty < 1 || tx > 6 || ty > 6)
			continue;
		if (cnt + 1 > dis[tx][ty])
			continue;

		dis[tx][ty] = cnt;
		pre[tx][ty][0] = x;
		pre[tx][ty][1] = y;
		DFS(tx, ty, cnt + 1);
	}
}

void output()
{
	stack<char> st;
	int x = ex, y = ey;
	int px = pre[x][y][0];
	int py = pre[x][y][1];

	while (true) 
	{
		if (x == px) 
		{
			if (py < y)
				st.push('E');
			else 
				st.push('W');
		}
		else 
		{
			if (px < x)
				st.push('S');
			else 
				st.push('N');
		}
		if (px == sx && py == sy)
			break;
		x = px;
		y = py;
		px = pre[x][y][0];
		py = pre[x][y][1];
	}

	while (!st.empty()) 
	{
		cout << st.top();
		st.pop();
	}
	cout << endl;
}

int main()
{
	while (cin >> sy >> sx)
	{
		if (sx == 0 && sy == 0)
			break;

		cin >> ey >> ex;
		for (int i = 0; i < MAXN; i++) //初始化
		{
			for (int j = 0; j < MAXN; j++)
			{
				dis[i][j] = INF;
				mp[i][j][0] = mp[i][j][1] = mp[i][j][2] = mp[i][j][3] = 0;
			}
		}
		for (int i = 0; i < 3; i++) //输入墙
		{
			cin >> wy1 >> wx1 >> wy2 >> wx2;
			if (wx1 == wx2) //墙为横向
			{
				for (int j = wy1 + 1; j <= wy2; j++)
				{
					mp[wx1][j][3] = 1;
					mp[wx1 + 1][j][1] = 1;
				}
			}
			else //墙为纵向
			{
				for (int j = wx1 + 1; j <= wx2; j++)
				{
					mp[j][wy2][0] = 1;
					mp[j][wy2 + 1][2] = 1;
				}
			}
		}

		DFS(sx, sy, 0);
		output();
	}
	return 0;
}
发布了325 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

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