问题 E: 挑战ACM迷宫
时间限制: 1 Sec 内存限制: 128 MB提交: 467 解决: 100
[ 提交][ 状态][ 讨论版]
题目描述
如下图所示的是一个由程序设计题目组成的ACM迷宫。迷宫的左上角是入口,右下角是出口。迷宫中每一个格子都有一个程序设计题目,挑战者要AC该题目后才能通过,大于0的数字表示AC该题目所需的最短时间。数字如果是0表示是陷阱,进去了就出不来。现在的问题是:求挑战者从入口到出口所需的最短时间。
输入
有多组测试实例。
对于每组测试实例,先输入一个数字n(1<n<=100),然后输入n*n个数字表示迷宫中的数字。
输出
对应输出挑战者从入口到出口所需的最短时间。
样例输入
10
1 0 2 1 2 3 4 2 2 5
2 1 0 1 3 2 5 7 2 1
1 1 1 0 1 1 1 3 2 3
1 2 1 1 0 1 1 1 2 3
1 1 2 0 2 0 2 3 2 3
2 2 2 2 3 2 0 2 3 2
3 2 2 2 1 1 1 0 1 1
0 1 1 3 0 1 1 2 3 2
2 0 1 1 2 2 2 2 2 2
3 2 3 2 3 2 3 2 3 2
5
1 2 1 2 5
1 3 2 4 5
2 1 0 2 5
2 1 1 2 1
2 4 1 1 2
样例输出
min=29
min=11
提示
刚开始用DFS写,无论怎么剪枝都是TLE,后来改用了BFS,果然效率快乐很多。下面有两份代码,第一份会TLE,第二份则可以AC
#include<stdio.h>
#define N 102
int min=1000000000;
int a[N][N];
int curPos_Sum[N][N];
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
int n;
void dfs(int i,int j,int sum) {
if(sum>=min||curPos_Sum[i][j]<sum) return;
curPos_Sum[i][j]=sum;
if((i==(n-1))&&(j==(n-1))) {
min=sum;
return;
} else {
for(int k=0;k<4;k++)
{
if(i+dir[k][0]>=0 && i+dir[k][0]< n && j+dir[k][1]>=0 && j+dir[k][1]<n && a[i+dir[k][0]][j+dir[k][1]]!=0)
dfs(i+dir[k][0],j+dir[k][1],sum+a[i+dir[k][0]][j+dir[k][1]]);
}
}
}
int main() {
int i,j;
while(scanf("%d",&n)!=EOF) {
min=1000000000;
for(i=0; i<n; i++)
for(j=0; j<n; j++) {
scanf("%d",&a[i][j]);
curPos_Sum[i][j]=1000000000;
}
dfs(0,0,a[0][0]);
printf("min=%d\n",min);
}
return 0;
}
思路是学长教的,但还是TLE,不知道为什么,还是怪自己能力有限,分析不出什么。所以自己用BFS写了一份,代码有点丑,大神不要喷。
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
struct data {
int x;
int y;
int cost;
};
int map1[102][102]; //地图
int lcount[102][102]; //该路线的在某点的时间消耗
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}}; //方向数组
queue <data> que;
void dfs() {
data location;
data st= {1,1,map1[1][1]};
que.push(st);
lcount[1][1]=map1[1][1];
while(!que.empty()) {
location=que.front();
que.pop();
if(location.cost <= lcount[location.x][location.y]) //剪枝叶,如果之前的线路时间花费比现在的小,则不往下搜
for(int i=0; i<4; i++) { //四个方向BFS
int newx,newy;
newx=location.x+dir[i][0];
newy=location.y+dir[i][1];
if(map1[newx][newy]!=0 ) {
if(lcount[newx][newy]==0) { //如果新加入的节点时间比原来的大,则不进队列,也是一种剪枝叶
lcount[newx][newy]=location.cost+map1[newx][newy];
data st= {newx,newy,lcount[newx][newy]};
que.push(st);
} else if (location.cost+map1[newx][newy]<lcount[newx][newy]) {
lcount[newx][newy]=location.cost+map1[newx][newy];
data st= {newx,newy,lcount[newx][newy]};
que.push(st);
}
}
}
}
}
int main() {
int n;
while(scanf("%d",&n)!=EOF) {
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++) {
scanf("%d",&map1[i][j]);
}
memset(lcount,0,sizeof(lcount));
dfs();
printf("min=%d\n",lcount[n][n]);
}
}