小明某天不小心进入了一个迷宫(如上图所示),请帮他计算走出迷宫的最少的时间。规定每走一格需要1个单位时间。如果不能走到出口,则输出impossible。每次能走的仅有上、下、左、右4个方向。
输入格式:
测试数据有多组,处理到文件尾。每组测试数据首先输入2个整数n,m(0
'd'代表该位置有怪物,需额外使用d(1≤d≤9)个单位时间消灭怪物后方可进入该位置。
输出格式:
对于每组测试,输出走出迷宫的最少时间,若不能走出则输出impossible。
输入样例:
4 4
S8..
.1.#
#.#.
...T
4 4
S...
#..#
..#.
2.#T
输出样例:
7
impossible
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
运行超时了,有无更优解
下面是我的代码
#include
using namespace std;
struct pos{
int x,y;
};
int steps;
const int M=100,N=100;
bool vis[M][N];
int m,n;
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
char maze[M][N];
int cnt;
bool cmp(pos a,pos b){
return maze[a.x][a.y]'S') time++;
if(s.x==t.x&&s.y==t.y)
{
cnt++;
if(steps>time) steps=time;
time=0;
return ;
}
if(maze[s.x][s.y]>='1'&&maze[s.x][s.y]<='9'){
time+=(maze[s.x][s.y]-'0');
}
vis[s.x][s.y]=true;
for(int i=0;i<4;i++){
pos p[4];
for(int j=0;j<4;j++){
p[j]={s.x+dir[j][0],s.y+dir[j][1]};
}
sort(p,p+4,cmp);
pos e=p[i];
if(e.x<0||e.x==m||e.y<0||e.y==n) continue;
if(vis[e.x][e.y]==true||maze[e.x][e.y]=='#') continue;
dfs(e,t,time);
vis[e.x][e.y]=false;
}
}
pos s,t;
void input(){
for(int i=0;i0;j>maze[i][j];
if(maze[i][j]=='S') s.x=i,s.y=j;
else if(maze[i][j]=='T') t.x=i,t.y=j;
}
}
}
int main (){
while(cin>>m>>n){
input();
fill(&vis[0][0],&vis[m-1][n-1]+1,false);
cnt=0;
steps=INT_MAX;
dfs(s,t,0);
if(cnt>0) cout<"impossible"<0;
}
#include<bits/stdc++.h>
using namespace std;
int pos[4][2]={-1,0,1,0,0,-1,0,1}; //可以走的位置
int ans;
char mg[102][102];
void findWay(int x,int y,int time)
{
if(mg[x][y]!='S'){
time++;
}
if(mg[x][y]=='T'){
ans=time<ans?time:ans;
return;
}
if(mg[x][y]>='1'&&mg[x][y]<='9'){
time+=(mg[x][y]-'0');
}
queue<int> point;
for(int i=0;i<4;i++){
if(mg[x+pos[i][0]][y+pos[i][1]]!='#'&&mg[x+pos[i][0]][y+pos[i][1]]!='S'){
point.push(x+pos[i][0]);
point.push(y+pos[i][1]);
}
}
int nx,ny;
char hs;
while(!point.empty()){
nx=point.front();
point.pop();
ny=point.front();
point.pop();
hs = mg[x][y];
mg[x][y]='#';
findWay(nx,ny,time);
mg[x][y]=hs;
}
}
int main()
{
int n,m;
int bx,by;
while(cin>>n>>m)
{
ans=n*m*9;
for(int i=0;i<=n+1;i++){
for(int j=0;j<=m+1;j++){
mg[i][j]='#';
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>mg[i][j];
if(mg[i][j]=='S'){
bx=i;
by=j;
}
}
}
findWay(bx,by,0);
if(ans==n*m*9){
cout<<"impossible"<<endl;
}else{
cout<<ans<<endl;
}
}
}