【深搜】城市交通

原题和广搜代码在这里

时间同样0ms。

3 6
+-+-+.+-+-+
|...|.....|
+-+.+-+-+-+
..|.......|
S-+-+-+.E-+
#endif

#include <iostream>
#include <cstring>
#include <queue>

#define SIZE 101
#define NUM 10001

using namespace std;

struct node
{
	int x, y;
};

char a[SIZE][SIZE];
int dir[SIZE][SIZE], res[NUM];
queue<node> q;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, 1, -1};
char resc[NUM];
char chs[4] = {'N', 'S', 'E', 'W'};
bool visited[SIZE][SIZE];
int best[SIZE][SIZE];

bool check(int x, int y, int dir)
{
	switch (a[x][y])
	{
		case '+':
			return true;
		case '-':
			return (dir > 1);
		case '|':
			return (dir < 2);
	}
	
	return false;
}

void dfs(int x, int y, int st, int d) // 深搜过程
{
	int i, r, c;
	if ((st >= best[x][y]) && (best[x][y])) // 步数超出了以前的最佳,不费时间了
	{
		return;
	}
	best[x][y] = st;
	dir[x][y] = d;
	for (i = 0; i < 4; i++)
	{
		r = x + dx[i];
		c = y + dy[i];
		if (check(x, y, i))
		{
			if ((!visited[r][c]) && (a[r][c] != '.')) // 如果满足条件
			{
				visited[r][c] = true; // 标为走过
				dfs(r, c, st + 1, i); // 则递归
			}
		}
	}
	
	return;
}

int main(int argc, char** argv)
{
	int n, m, i, j, r, c, sx, sy, ex, ey, k = 0, ta, tb;
	bool flag = false;
	
	scanf("%d%d", &n, &m);
	
	n = n * 2 - 1;
	m = m * 2 - 1;
	memset(a, '.', sizeof (a));
	
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= m; j++)
		{
			cin >> a[i][j];
			switch (a[i][j])
			{
				case 'S':
					sx = i;
					sy = j;
					a[i][j] = '+';
					break;
				case 'E':
					ex = i;
					ey = j;
					a[i][j] = '+';
					break;
			}
		}
	}
	
	visited[sx][sy] = true;
	dfs(sx, sy, 0, -1);
	/*
	q.push({sx, sy});
	while (!q.empty())
	{
		for (i = 0; i < 4; i++)
		{
			r = q.front().x + dx[i];
			c = q.front().y + dy[i];
			if ((r == ex) && (c == ey))
			{
				flag = true;
				dir[r][c] = i;
				break;
			}
			if ((!visited[r][c]) && (a[r][c] != '.'))
			{
				if (check(q.front().x, q.front().y, i))
				{
					dir[r][c] = i;
					visited[r][c] = true;
					q.push({r, c});
				}
			}
		}
		if (flag)
		{
			break;
		}
		q.pop();
	}
	*/
	i = -2;
	m = n = 0;
	r = ex;
	c = ey;
	do
	{
		if (a[r][c] == '+')
		{
			m++;
		}
		if (dir[r][c] != i)
		{
			ta = r;
			tb = c;
			n = m;
			if (i != -2)
			{
				res[++k] = m;
				resc[k] = chs[i];
			}
			m = 0;
			i = dir[r][c];
		}
		j = dir[r][c];
		r -= dx[j];
		c -= dy[j];
	} while (dir[r][c] != -1);
	res[++k] = 0;
	for ( ; ; )
	{
		sx += dx[j];
		sy += dy[j];
		if (a[sx][sy] == '+')
		{
			res[k]++;
		}
		if ((sx == ta) && (sy == tb))
		{
			break;
		}
	}
	resc[k] = chs[j];
	
	for (i = k; i >= 1; i--)
	{
		printf("%c %d\n", resc[i], res[i]);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/81005628