So below is my submission for TGIPL6 expert level question link :
#include<stdio.h>
#include<string.h>
//Assume following return types while writing the code for this question.
int output1[100];
int r,c,done=0,temp_op=-999,num=0;
struct s
{
char a;
int b,d;
}mat[100][100];
void magic()
{
int temp=0,i,j;num++;
if(done ==1)return;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
if(mat[i][j].a=='S'&&mat[i][j].d==0)
{
if(i+1<r)
{
if(mat[i+1][j].a=='P'&&mat[i+1][j].b==0){
mat[i+1][j].b=1;
temp=1;
}
}
if(j+1<c)
{
if(mat[i][j+1].a=='P'&&mat[i][j+1].b==0){
mat[i][j+1].b=1;
temp=1;
}
}
if(i-1>=0)
{
if(mat[i-1][j].a=='P'&&mat[i-1][j].b==0){
mat[i-1][j].b=1;
temp=1;
}
}
if(j-1>=0)
{
if(mat[i][j-1].a=='P'&&mat[i][j-1].b==0){
mat[i][j-1].b=1;
temp=1;
}
}mat[i][j].d=1;
}
else if((mat[i][j].a=='P'||mat[i][j].a=='p')&&mat[i][j].b>=1&&mat[i][j].d==0)
{
if(i+1<r)
{
if(mat[i+1][j].a=='P'&&(mat[i+1][j].b==0||mat[i+1][j].b>mat[i][j].b+1)){
mat[i+1][j].b=mat[i][j].b+1;
temp=1;
}
else if(mat[i+1][j].a=='E'&&(mat[i+1][j].b==0||mat[i+1][j].b>mat[i][j].b+1)){
mat[i+1][j].b=mat[i][j].b+1;
temp=1;
done=1;
temp_op=mat[i][j].b;
return;
}
}
if(j+1<c)
{
if(mat[i][j+1].a=='P'&&mat[i][j+1].b==0){
mat[i][j+1].b=mat[i][j].b+1;
temp=1;
}
else if(mat[i][j+1].a=='E'&&mat[i][j+1].b==0){
mat[i][j+1].b=mat[i][j].b+1;
temp=1;
done=1;
temp_op=mat[i][j].b;
return;
}
}
if(i-1>=0)
{
if(mat[i-1][j].a=='P'&&mat[i-1][j].b==0){
mat[i-1][j].b=mat[i][j].b+1;
temp=1;
}
else if(mat[i-1][j].a=='E'&&mat[i-1][j].b==0){
mat[i-1][j].b=mat[i][j].b+1;
temp=1;
done=1;
temp_op=mat[i][j].b;
return;
}
}
if(j-1>=0)
{
if(mat[i][j-1].a=='P'&&mat[i][j-1].b==0){
mat[i][j-1].b=mat[i][j].b+1;
temp=1;
}
else if(mat[i][j-1].a=='E'&&(mat[i][j-1].b==0)){
mat[i][j-1].b=mat[i][j].b+1;
temp=1;
done=1;
temp_op=mat[i][j].b;
return;
}
}mat[i][j].d=1;
}
}
if(temp)
magic();
}
void Escape_Maze(int input1,char* input2)
{
int i,j=1,k,l,cs,rs,ce,re,sum,ns=0,ne=0,nw=0,np=0;
//char mat[51][51];
char *p,*p1;
for(i=0;i<input1;i++)
{
if(i==0)
{
p=strtok(input2," ,{};:.()\"[]-!@#$%^&*_=+|\\'<>?`~");
p1=strtok(NULL," ,{};:.()\"[]-!@#$%^&*_=+|\\'<>?`~");
}
else
{
p=strtok(NULL," ,{};:.()\"[]-!@#$%^&*_=+|\\'<>?`~");
p1=strtok(NULL," ,{};:.()\"[]-!@#$%^&*_=+|\\'<>?`~");
}
sscanf(p,"%d",&r);
sscanf(p1,"%d",&c);
for(k=0;k<r;k++){
for(l=0;l<c;l++)
{
p=strtok(NULL," ,{};:.()\"[]-!@#$%^&*_=+|\\'<>?`~");
mat[k][l].a=p[0];
mat[k][l].b=0;
mat[k][l].d=0;
if(p[0]=='S'||p[0]=='s')
{ns++;
mat[k][l].a='S';
if(k!=0&&l!=0&&k!=r-1&&l!=c-1)
ns=10;
}
else if(p[0]=='E'||p[0]=='e'){
ne++;
mat[k][l].a='E';
if(k!=0&&l!=0&&k!=r-1&&l!=c-1)
ne=10;
}
else if(p[0]=='P'||p[0]=='p')
{np++;
mat[k][l].a='P';
}
else if(p[0]=='W')
nw++;
else
mat[k][l].a='P';
}
}
if(ns==1&&ne==1&&input1<=10&&r<=50&&c<=50&&np>0){
magic();
output1[i]=temp_op;
}
else
output1[i]=-999;
done =0;
ns=ne=nw=0;
temp_op=-999;num=0;
}
//Write code here
}
No comments:
Post a Comment