Problem Link
Problem Type : Single Source Shortest Path on Unweighted Graph (BFS).
Difficulty Level : Easy
Author : Imdad
Briefly problem statement
A 3d maze is given. We have to find out shortest path between a start point and a end point. Simple BFS can do the trick.
Here, is the C++ implementation of this problem.
Problem Type : Single Source Shortest Path on Unweighted Graph (BFS).
Difficulty Level : Easy
Author : Imdad
Briefly problem statement
A 3d maze is given. We have to find out shortest path between a start point and a end point. Simple BFS can do the trick.
Here, is the C++ implementation of this problem.
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
#define sz 31
int L,R,C;
char in[sz][sz][sz];
bool used[sz][sz][sz];
typedef struct{
int L,R,C;
int step;
}data;
data st,en,tmp,cur;
int solve(data start){
queueQ;
int dr[] = {0,0,-1,1};
int dc[] = {-1,1,0,0};
int i;
memset(used,true,sizeof(used));
Q.push(start);
used[st.L][st.R][st.C] = false;
while(!Q.empty()){
cur = Q.front();
Q.pop();
if(in[cur.L][cur.R][cur.C] == 'E')
return cur.step;
//used[cur.L][cur.R][cur.C] = false;
for(i = 0; i < 4; i++){
tmp = cur;
tmp.R += dr[i];
tmp.C += dc[i];
if(tmp.R < 0 || tmp.R >= R)
continue;
if(tmp.C < 0 || tmp.C >= C)
continue;
if(used[tmp.L][tmp.R][tmp.C] && in[tmp.L][tmp.R][tmp.C] != '#'){
tmp.step = cur.step + 1;
Q.push(tmp);
used[tmp.L][tmp.R][tmp.C] = false;
}
}
if(cur.L - 1 >= 0){
tmp = cur;
tmp.L--;
if(used[tmp.L][tmp.R][tmp.C] && in[tmp.L][tmp.R][tmp.C] != '#'){
tmp.step = cur.step + 1;
Q.push(tmp);
used[tmp.L][tmp.R][tmp.C] = false;
}
}
if(cur.L + 1 < L){
tmp = cur;
tmp.L++;
if(used[tmp.L][tmp.R][tmp.C] && in[tmp.L][tmp.R][tmp.C] != '#'){
tmp.step = cur.step + 1;
Q.push(tmp);
used[tmp.L][tmp.R][tmp.C] = false;
}
}
}
return -1;
}
int main(){
int i,j,k,ans;
//freopen("i.txt","r",stdin);
while(scanf("%d %d %d",&L,&R,&C) && !(!L && !R && !C) ){
for(i = 0; i < L; i++){
getchar();
for(j = 0; j < R; j++){
for(k = 0; k < C; k++){
in[i][j][k] = getchar();
if(in[i][j][k] == 'S'){
st.L = i;
st.R = j;
st.C = k;
st.step = 0;
}
}
getchar();
}
}
ans = solve(st);
if(ans == -1)
printf("Trapped!\n");
else
printf("Escaped in %d minute(s).\n",ans);
}
return 0;
}

No comments:
Post a Comment