HDU 1240三次元bfs

1653 ワード

#include <iostream>
#include <queue>
using namespace std;
int map[15][15][15];
int flag, a, b, c, d, e, f, n;
char str[15][15][15];
int dir[6][3] = {{1,0,0}, {-1,0,0}, {0,1,0}, 
				{0,-1,0}, {0,0,1}, {0,0,-1}};

struct node
{
	int x, y, z, step;
};

int judge(int x, int y, int z)
{
	if(x >= 0 && x < n && y >= 0 && y < n && z >= 0 
		&& z < n && map[x][y][z] ==0 && str[x][y][z] == 'O')
		return 1;
	return 0;
}

void bfs()
{
	int i, x, y, z;
	queue<node> q;
	node cur, next;
	memset(map, 0, sizeof(map));
	cur.x = a;
	cur.y = b;
	cur.z = c;
	cur.step = 0;
	q.push(cur);
	map[a][b][c] = 1;
	if(a == d && b == e && c == f)
	{
		printf("%d 0
", n); return; } while(!q.empty()) { cur = q.front(); q.pop(); for(i = 0; i < 6; i++) { next.x = x = cur.x + dir[i][0]; next.y = y = cur.y + dir[i][1]; next.z = z = cur.z + dir[i][2]; if(judge(x,y,z)) { map[x][y][z] = 1; next.step = cur.step + 1; if(x == d && y == e && z == f) { printf("%d %d
", n, next.step); return; } q.push(next); } } } printf("NO ROUTE
"); } int main() { int i, j; char s[15], t[15]; while(scanf("%s %d", s, &n) == 2) { for(i = 0; i < n; i++) for(j = 0; j < n; j++) scanf("%s", str[i][j]); scanf("%d%d%d", &a, &b, &c); scanf("%d%d%d", &d, &e, &f); str[d][e][f] = 'O'; bfs(); scanf("%s", t); } return 0; }