同一天内两次站外题求助awa
原题链接http://noi.openjudge.cn/ch005/2727/\
总是TLE的代码:
//第一次自己做最小路线
//会超时
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
#define maxn 22
using namespace std;
int _min = 200; //用于记录可行路线所走的最小方格数(总不能超20*20)
int start_x,start_y; //李逍遥初始坐标
int target_x,target_y; //仙药所处坐标
char a[maxn][maxn]; //记录地图
int m,n; //记录行和列,这次给的比较良心。
void dfs(int x,int y, int num){ //num表示当前走过的方格数;
if(num >= _min){
return; //如果此时num大于最小值了,继续往下走将毫无意义
}
if(a[y][x] == '*'){
if(_min > num){
_min = num; //更新最小值
}
return;
}
//如果没到仙药
if(a[y][x+1] != '#'){
a[y][x] = '#'; //占位,表示走过了
dfs(x+1,y,num+1);
a[y][x] = '.'; //回来重置值
}
if(a[y][x-1] != '#'){
a[y][x] = '#';
dfs(x-1,y,num+1);
a[y][x] = '.';
}
if(a[y+1][x] != '#'){
a[y][x] = '#';
dfs(x,y+1,num+1);
a[y][x] = '.';
}
if(a[y-1][x] != '#'){
a[y][x] = '#';
dfs(x,y-1,num+1);
a[y][x] = '.';
}
return;
}
int main()
{
while (true){
cin >> m >> n;
if(m == 0 && n == 0){
return 0;
}
for(int i = 0; i<= m+1; i++){
for(int j = 0; j <= n+1; j++){
a[i][j] = '#';
}
}
for(int i = 1; i<= m; i++){
for(int j = 1; j <= n; j++){
cin>> a[i][j];
if(a[i][j] == '@'){
start_y = i;
start_x = j;
}
if(a[i][j] == '*'){
target_y = i;
target_x = j;
}
}
}
dfs(start_x,start_y,0);
if(_min == 400){
cout << -1 << endl;
}else{
cout << _min << endl;
}
_min = 400;
}
return 0;
}
我该如何优化。 谢谢!