这有一个迷宫,有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
思路:看到本题首先想到就是dfs(深搜)根据递归求出答案
#include<stdio.h> int x1,y1,x2,y2,ans=100; int map[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} },s[9][9]; void dfs(int i,int j,int count) { if(i<0||j<0||i>8||j>8||map[i][j]==1||s[i][j]==1||count>ans) return; if(i==x2 && j==y2) { ans=count; return; } s[i][j]=1; dfs(i,j-1,count+1); dfs(i-1,j,count+1); dfs(i+1,j,count+1); dfs(i,j+1,count+1); s[i][j]=0; } int main() { int n; scanf("%d",&n); while(n--) { scanf("%d%d%d%d",&x1,&y1,&x2,&y2); ans=100; dfs(x1,y1,0); printf("%d\n",ans); } return 0; }
原文地址:http://blog.csdn.net/u013238646/article/details/45077507