迷宫 (BFS)

《挑战程序设计》 P34

第一次使用pair

1.头文件:<utility>
2.成员:mypair.first, mypair.second
3.运算符:<、>、<=、>=、==、!=,其规则是先比较first,first相等时再比较second
4.相关函数:make_pair 例如:p=make_pair(1,1); q.push(make_pair(1,1));

#include <iostream>
#include <utility>
#include <cstdio>
#include <queue>

using namespace std;

const int INF = 100000000;

typedef pair<int, int> P;

const int N = 100;

char maze[N][N + 1];
int n, m;
int sx, sy;
int gx, gy;

int d[N][N]; 			//记录到各个位置的最短距离

int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

int bfs()
{
	queue<P> que;
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < m; ++j)
			d[i][j] = INF;
	que.push(P(sx, sy));
	d[sx][sy] = 0;

	while (que.size()) {
		P p = que.front();
		que.pop();
		if (p.first == gx && p.second == gy) break;

		for (int i = 0; i < 4; ++i) {
			int nx = p.first + dx[i];
			int ny = p.second + dy[i];
			if (nx < n && nx >= 0 && ny < m && ny >= 0 &&
					maze[nx][ny] != '#' && d[nx][ny] == INF) {
				d[nx][ny] = d[p.first][p.second] + 1;
				que.push(P(nx, ny));
			}
		}
	}
	return d[gx][gy];
}

void solve()
{
	scanf("%d%d", &n, &m);
	for (int i = 0; i < n; ++i) {
		getchar();
		for (int j = 0; j < m; ++j) {
			scanf("%c", &maze[i][j]);
			if (maze[i][j] == 'S') sx = i, sy = j;
			if (maze[i][j] == 'G') gx = i, gy = j;
		}
	}
	int res = bfs();
	printf("%d\n", res);
}

int main()
{
    solve();
    return 0;
}

/****************
Input:
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#

Output:
22
*****************/

  

上一篇:BZOJ 3550: [ONTAK2010]Vacation [单纯形法]


下一篇:Python爬虫之selenium的使用(八)