nyoj58 最少步数

 1 #include<stdio.h>

 2 int ans,sx,sy,ex,ey;

 3 bool vis[9][9],map[9][9]={

 4  1,1,1,1,1,1,1,1,1,

 5  1,0,0,1,0,0,1,0,1,

 6  1,0,0,1,1,0,0,0,1,

 7  1,0,1,0,1,1,0,1,1,

 8  1,0,0,0,0,1,0,0,1,

 9  1,1,0,1,0,1,0,0,1,

10  1,1,0,1,0,1,0,0,1,

11  1,1,0,1,0,0,0,0,1,

12  1,1,1,1,1,1,1,1,1

13 };

14 void dfs(int i,int j,int cnt)

15 {

16     if(i<0||j<0||i>8||j>8||vis[i][j]||map[i][j]||cnt>=ans) return;

17     if(i==ex&&j==ey){

18         ans=cnt;

19         return;

20     }

21     vis[i][j]=1;

22     dfs(i,j-1,cnt+1);

23     dfs(i-1,j,cnt+1);

24     dfs(i,j+1,cnt+1);

25     dfs(i+1,j,cnt+1);

26     vis[i][j]=0;

27 }

28 int main()

29 {

30     int n;

31     scanf("%d",&n);

32     while(n--){

33         scanf("%d%d%d%d",&sx,&sy,&ex,&ey);

34         ans=100;

35         dfs(sx,sy,0);

36         printf("%d\n",ans);

37     }

38     return 0;

39 }

//递归

你可能感兴趣的:(OJ)