#20659: TLE:第四個測資超時,是因為用遞迴寫法的關係嗎


john211710@gmail.com (QQ Q)

學校 : 不指定學校
編號 : 108102
來源 : [42.73.158.147]
最後登入時間 :
2021-02-10 15:54:40
a982. 迷宮問題#1 | From: [42.73.76.40] | 發表日期 : 2020-02-17 17:54

#include<iostream>
using namespace std;

int data_read(int n,int **maze)//讀取測資
{
char tem;
for(int i=0; i<n; i++)
{
maze[i]=new int[n];
for(int j=0; j<n; j++)
{
cin>>tem;
if(tem=='#')
{
maze[i][j]=1;
}
else if(tem=='.')
{
maze[i][j]=0;
}
}
}
}

typedef struct
{
int x;
int y;
} point;

point point_read(int x,int y)
{
point p= {x,y};
return p;
}

void visit(int **maze,point start,point end,int current_path,int *final_path)
{
if(maze[start.y][start.x]!=1)
{
maze[start.y][start.x]=1;
current_path++;
if(start.x==end.x&&start.y==end.y)
{
if(current_path<*final_path)
{
*final_path=current_path;
}
}
else
{
visit(maze,point_read(start.x+1,start.y),end,current_path,final_path);
visit(maze,point_read(start.x,start.y+1),end,current_path,final_path);
visit(maze,point_read(start.x-1,start.y),end,current_path,final_path);
visit(maze,point_read(start.x,start.y-1),end,current_path,final_path);
}
maze[start.y][start.x]=0;
current_path--;
}
}

int main()
{
for(int n; cin>>n;)
{
int **maze=new int*[n],current_path=0,final_path=n*n;
data_read(n,maze);
visit(maze,point_read(1,1),point_read(n-2,n-2),current_path,&final_path);
if(final_path!=n*n)
{
cout<<final_path<<endl;
}
else
{
cout<<"No solution!"<<endl;
}

}
return 0;
}

 

 
ZeroJudge Forum