NC201613. Jelly
描述
输入描述
第一行:一个整数n。
接下来n层,每组n行,每行n列,表示果冻(i,j,k)的情况(如题目描述所述)。
数据满足:,保证果冻(1,1,1)不是Nancy不愿意吃的。
输出描述
如果可以到达(n,n,n),请输出路上吃的果冻数量,否则请输出-1。
示例1
输入:
2 .* .. *. ..
输出:
4
Java 解法, 执行用时: 638ms, 内存消耗: 27124K, 提交时间: 2023-08-12 10:30:04
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static int N = 110; static char[][][] gd = new char[N][N][N]; static Queue<D> q = new LinkedList<D>(); static int[] dx = { 0, 0, 1, -1, 0, 0 }; static int[] dy = { 0, 0, 0, 0, 1, -1 }; static int[] dz = { 1, -1, 0, 0, 0, 0 }; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) gd[i][j] = sc.next().toCharArray(); q.add(new D(0, 0, 0, 0)); gd[0][0][0] = '*'; while (!q.isEmpty()) { D d = q.poll(); int nx, ny, nz; for (int i = 0; i < 6; i++) { if(d.x==n-1&&d.y==n-1&&d.z==n-1) { System.out.println(++d.step); return; } nx = d.x + dx[i]; ny = d.y + dy[i]; nz = d.z + dz[i]; if(nx<0||nx>=n||ny<0||ny>=n||nz<0||nz>=n) continue; if(gd[nx][ny][nz] == '*') continue; q.add(new D(nx, ny, nz, d.step+1)); gd[nx][ny][nz] = '*'; } } System.out.println(-1); } } class D { int x; int y; int z; int step; public D(int x, int y, int z, int step) { super(); this.x = x; this.y = y; this.z = z; this.step = step; } }
C++ 解法, 执行用时: 63ms, 内存消耗: 13012K, 提交时间: 2023-08-12 10:29:14
#include<bits/stdc++.h> using namespace std; struct node { int x,y,z,h; }Q[1000005]; int dx[]={1,-1,0,0,0,0},dy[]={0,0,1,-1,0,0},dz[]={0,0,0,0,1,-1}; char R[105][105][105]; bool F=0,V[105][105][105]={0}; int main() { int i,j,k,n,x,y,z,h,r=1,f=0,X,Y,Z; scanf("%d",&n); for(i=0;i<n;i++) for(j=0;j<n;j++)scanf("%s",R[i][j]); Q[0].h=V[0][0][0]=1,Q[0].x=Q[0].y=Q[0].z=0; while(r!=f) { x=Q[f].x,y=Q[f].y,z=Q[f].z,h=Q[f++].h; if(x==n-1&&y==n-1&&z==n-1) { F=1; break; } for(i=0;i<6;i++) { X=x+dx[i],Y=y+dy[i],Z=z+dz[i]; if(X<0||X>=n||Y<0||Y>=n||Z<0||Z>=n||V[X][Y][Z]||R[X][Y][Z]=='*')continue; V[X][Y][Z]=1,Q[r].x=X,Q[r].y=Y,Q[r].z=Z,Q[r++].h=h+1; } } if(!F)h=-1; printf("%d\n",h); return 0; }