您的位置:首页 > 其它

NYOJ 58 最少步数问题

2016-08-01 18:29 246 查看
//修改版
#include<stdio.h>#include<string.h>int arr[9][9] = {1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,};int book[9][9];int Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};int starx, stary, endx, endy;int min_step = 999999;void DFS(int x, int y,int step){if(x == endx && y == endy){if(step < min_step)min_step = step;return ;}int i,tempx,tempy;for(i = 0;i<4;i++){tempx = x + Next[i][0];tempy = y + Next[i][1];if(tempx < 1 || tempx > 8 || tempy < 1 || tempy > 8)continue;if(arr[tempx][tempy] == 0 && book[tempx][tempy] == 0){book[tempx][tempy] = 1;DFS(tempx,tempy,step + 1);book[tempx][tempy] = 0;}}return ;}int main(){int N;scanf("%d",&N);while(N--){min_step = 999999;scanf("%d %d %d %d",&starx,&stary,&endx,&endy);memset(book, 0, sizeof(book));book[starx][stary] = 1;DFS(starx,stary,0);printf("%d\n",min_step);}return 0;} 
//两个月后重新看这个感觉简单了很多,优化后:#include<cstdio>#define min(x,y) x>y?y:xint arr[9][9] = {1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,};int a, b, ea, eb, min_step;void dfs(int x, int y, int step){if(arr[x][y])return ;if(x == ea && y == eb){min_step = min(step,min_step);return ;}arr[x][y] = 1;dfs(x+1,y,step+1);dfs(x,y+1,step+1);dfs(x-1,y,step+1);dfs(x,y-1,step+1);arr[x][y] = 0;}int main(){int n;scanf("%d",&n);while(n--){min_step = 0xfffff;scanf("%d%d%d%d",&a,&b,&ea,&eb);dfs(a, b, 0);printf("%d\n",min_step);}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: