当前位置: 代码迷 >> 综合 >> uva-439 - Knight Moves
  详细解决方案

uva-439 - Knight Moves

热度:80   发布时间:2023-12-19 11:38:19.0

用的DFS。


#include<stdio.h>
int x,y;
int max=6;
int pan(int a,int b)
{if(a>=0&&a<8&&b>=0&&b<8)return 1;return 0;
}
void dfs(int a,int b,int sum)
{if(sum>=max)return ;if(a==x&&b==y&&sum<max){max=sum;return ;}if(pan(a+2,b+1))dfs(a+2,b+1,sum+1);if(pan(a+2,b-1))dfs(a+2,b-1,sum+1);if(pan(a-2,b-1))dfs(a-2,b-1,sum+1);if(pan(a-2,b+1))dfs(a-2,b+1,sum+1);if(pan(a-1,b-2))dfs(a-1,b-2,sum+1);if(pan(a-1,b+2))dfs(a-1,b+2,sum+1);if(pan(a+1,b-2))dfs(a+1,b-2,sum+1);if(pan(a+1,b+2))dfs(a+1,b+2,sum+1);
}
int main()
{int x1,y1;char str1[100],str2[100];while(scanf("%s%s",str1,str2)!=EOF){max=6;x1=str1[0]-'a';y1=str1[1]-'1';x=str2[0]-'a';y=str2[1]-'1';dfs(x1,y1,0);printf("To get from %s to %s takes %d knight moves.\n",str1,str2,max);}return 0;
}