标签:
这有一个迷宫,有0~8行和0~8列:
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
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
2 3 1 5 7 3 1 6 7
12 11
方法一:
#include<stdio.h> #include<string.h> int a,b,c,d; int min; int book[9][9]; int s[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} }; void dfs(int x,int y,int step) { int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; if(x==c&&y==d) { if(step<min) min=step; return ; } int k,tx,ty; for(k=0;k<=3;k++) { tx=x+next[k][0]; ty=y+next[k][1]; if(tx>8||ty>8||tx<0||ty<0) continue ; if(s[tx][ty]==0&&book[tx][ty]==0) { book[tx][ty]=1; dfs(tx,ty,step+1); book[tx][ty]=0; } } return ; } int main(void) { int N,i,j; scanf("%d",&N); while(N--) { memset(book,0,sizeof(book)); min=99999999; scanf("%d%d%d%d",&a,&b,&c,&d); book[a][b]=1; dfs(a,b,0); printf("%d\n",min); } return 0; }
方法二:
#include<stdio.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 a,b,c,d,m; void dfs(int i,int j,int s) { if(arr[i][j]==1) return ; if(i==c&&j==d) { m=s>m?m:s; return ; } s=s+1; arr[i][j]=1; dfs(i+1,j,s); dfs(i,j+1,s); dfs(i-1,j,s); dfs(i,j-1,s); arr[i][j]=0; } int main() { int t; scanf("%d",&t); while(t--) { m=20000000; scanf("%d%d%d%d",&a,&b,&c,&d); dfs(a,b,0); printf("%d\n",m); } return 0; }
标签:
原文地址:http://blog.csdn.net/qq_16997551/article/details/45227013