【BFS】HDOJ 1026 Ignatius and the Princess I

BFS+栈+队列,怼了一晚上终于怼出来了。

#include 
#include 
#include 
#include 
#include 
using namespace std;

char maps[105][105];
int n, m;
int dir[4][2] = { 1,0,0,1,-1,0,0,-1 };

typedef struct node
{
	int x;
	int y;
	int prex;
	int prey;
	int cost;
}node;
node p[105][105];

bool check(int x, int y)
{
	if (maps[x][y] != 'X' && x >= 0 && x < n && y >= 0 && y < m)
		return true;
	return false;
}

void print_path()
{
	stacks;
	node a,b;
	printf("It takes %d seconds to reach the target position, let me show you the way.\n", p[n - 1][m - 1].cost);
	a = p[n - 1][m - 1];
	while (1)
	{
		if (a.x == 0 && a.y == 0) break;
		s.push(a);
		a = p[a.prex][a.prey];
	}
	a = p[0][0];
	int cnt = 1;
	while (!s.empty())
	{
		b = s.top();
		s.pop();
		if (maps[b.x][b.y] == '.')
		{
			printf("%d", cnt);
			printf("s:(%d,%d)->(%d,%d)\n", a.x, a.y, b.x, b.y);
			cnt++;
		}
		else
		{
			int j = maps[b.x][b.y] - '0';
			printf("%d", cnt);
			printf("s:(%d,%d)->(%d,%d)\n", a.x, a.y, b.x, b.y);
			cnt++;
			while (j--)
			{
				printf("%d", cnt);
				printf("s:FIGHT AT (%d,%d)\n", b.x, b.y);
				cnt++;
			}
		}
		a = b;
	}
	cout << "FINISH" << endl;
}

void bfs()
{
	queueq;
	node a, b;
	a.x = a.y = a.prex = a.prey = a.cost = 0;
	p[0][0] = a;
	q.push(a);
	int i, j;
	while (!q.empty())
	{
		a = q.front();
		q.pop();
		if (a.x == n - 1 && a.y == m - 1)
		{
			print_path();
			return;
		}
		for (i = 0; i < 4; i++)
		{
			b.x = a.x + dir[i][0];
			b.y = a.y + dir[i][1];
			if (!check(b.x, b.y)) continue;
			else
			{
				if (maps[b.x][b.y] != '.')
					j = maps[b.x][b.y] - '0';
				else j = 0;
				b.prex = a.x;
				b.prey = a.y;
				b.cost = a.cost + 1 + j;
			}
			if (b.cost < p[b.x][b.y].cost || p[b.x][b.y].cost == -1)
			{
				p[b.x][b.y] = b;
				q.push(b);
			}
		}
	}
	if (p[n - 1][m - 1].cost == -1)
	{
		printf("God please help our poor hero.\nFINISH\n");
		return;
	}
}

int main()
{
	while (cin >> n >> m)
	{
		int i, j;
		for (i = 0; i < n; i++)
		{
			for (j = 0; j < m; j++)
			{
				cin >> maps[i][j];
				p[i][j].cost = -1;
			}
		}
		bfs();
	}
	return 0;
}


你可能感兴趣的:(BFS)