hduoj1253胜利大逃亡
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1253
首次见识三维bfs的第一题,有必要记录一下;
题目思路:
和二维bfs差不多,需要注意的是多开一个z的同时所有的坐标都要按三维坐标运算;
1 #include<bits/stdc++.h> 2 using namespace std; 3 bool vis[50][50][50]; 4 int mapp[50][50][50];//保存立方体信息 5 struct node {// 6 int x, y, z; 7 int minn; 8 }; 9 queue<node> Q;//队列中的元素为状态 10 int dir[6][3] = {//坐标变换数组,由坐标扩展得到的新坐标均可通过(x+go[i][0],y+go[i][1],z+go[i][2]) 11 1,0,0, 12 -1,0,0, 13 0,1,0, 14 0,-1,0, 15 0,0,1, 16 0,0,-1 17 }; 18 int BFS(int a, int b, int c) {//广度优先搜索 19 memset(vis,0,sizeof(vis)); 20 queue<node> Q;//队列中的元素为状态queue<node> Q;//队列中的元素为状态 21 vis[0][0][0] = true; 22 node now; 23 now.minn = now.y = now.x = now.z = 0; 24 Q.push(now); 25 while (!Q.empty()) {//当队列中仍有元素可以扩展时循环 26 now = Q.front();//得到队头状态 27 Q.pop();//从队列弹出队头状态 28 if (now.x == a - 1 && now.y == b - 1 && now.z == c - 1) 29 return now.minn;//若改坐标为终点,直接返回其耗时 30 for (int i = 0; i < 6; i++) {//依次扩展其六个相邻节点 31 int nx = now.x + dir[i][0]; 32 int ny = now.y + dir[i][1]; 33 int nz = now.z + dir[i][2]; 34 if (nx < 0 || nx >= a || ny < 0 || ny >= b || nz < 0 || nz >= c) continue; 35 if (vis[nx][ny][nz] == 1) continue;//该位置为墙,则丢弃 36 if (mapp[nx][ny][nz] == 1) continue;//包含该位置的状态已经被得到,丢弃 37 node tmp;//新状态 38 tmp.x = nx; 39 tmp.y = ny; 40 tmp.z = nz;//新状态包含的坐标 41 tmp.minn = now.minn + 1;//新状态的耗时 42 vis[tmp.x][tmp.y][tmp.z] = true;//标记该坐标 43 Q.push(tmp);//将该状态放入队列 44 } 45 } 46 return -1;//所有状态被查找完后,仍得不到所需坐标,则返回-1 47 } 48 int main() { 49 int T; 50 scanf("%d", &T); 51 while (T--) { 52 int a, b, c, t; 53 scanf("%d%d%d%d", &a, &b, &c, &t);//输入 54 for (int i = 0; i < a; i++) { 55 for (int j = 0; j < b; j++) { 56 for (int k = 0; k < c; k++) { 57 scanf("%d", &mapp[i][j][k]);//输入立方体信息 58 } 59 } 60 } 61 int res = BFS(a, b, c); 62 if (res <= t) printf("%d\n", res); 63 else printf("-1\n"); 64 } 65 return 0; 66 }
本文来自博客园,作者:江上舟摇,转载请注明原文链接:https://www.cnblogs.com/LQS-blog/p/16265466.html