先看题目:https://ac.nowcoder.com/acm/problem/201613
题目描述:
三维果冻中,从(1,1,1)开始吃,能避开障碍吃到(n,n,n)的最小果冻数。
解题思路:
管它是几维,改改方向数组,然后直接bfs最短路径呗~
代码:
#include<bits/stdc++.h> using namespace std; int n; int dis[110][110][110]; bool mp[110][110][110]; int dir[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}}; struct node{ int x,y,z; }; queue<node> q; int bfs() { q.push({1,1,1}); dis[1][1][1]=1; while(!q.empty()) { node tmp = q.front(); q.pop(); for(int i = 0; i < 6; i++){ int dx = tmp.x+dir[i][0]; int dy = tmp.y+dir[i][1]; int dz = tmp.z+dir[i][2]; if(dx < 1 || dx > n || dy < 1 || dy > n || dz < 1 || dz > n) continue; if(mp[dx][dy][dz] == 0) continue; if(dis[dx][dy][dz] != 0) continue; dis[dx][dy][dz]=dis[tmp.x][tmp.y][tmp.z]+1; if(dx == n && dy == n && dz == n) return 1; q.push({dx,dy,dz}); } } return 0; } int main() { scanf("%d",&n); for(int i = 1 ; i <= n; i++) for(int j = 1; j <= n; j++) for(int k = 1; k <= n; k++) { char c; scanf(" %c",&c); if(c == '.') {mp[i][j][k] = 1;} else if(c == '*') {mp[i][j][k] = 0;} } if(bfs()) printf("%d\n",dis[n][n][n]); else printf("-1\n"); }