DFS的模板题
题目链接点击打开链接#include<iostream> #include<cstring> #include<cstdio> #include<queue> #define MM(x,y) memset(x,y,sizeof(x)) using namespace std; struct node { int x; int y; int pos; }; queue<node>a; char e[5],s[5]; int vis[30][30]; int dir[8][2]={{1,2},{2,1},{1,-2},{-2,1},{-1,2},{2,-1},{-1,-2},{-2,-1}}; int ex,ey,sx,sy; int dfs() { while(!a.empty()) a.pop(); int i; node now,next; now.x=sx; now.y=sy; now.pos=0; MM(vis,0); vis[sx][sy]=1; a.push(now); while(!a.empty()) { now=a.front(); a.pop(); if(now.x==ex&&now.y==ey) return now.pos; else { for(i=0;i<8;i++) { int tx=now.x+dir[i][0]; int ty=now.y+dir[i][1]; if(tx>=1&&tx<=8&&ty>=1&&ty<=8&&!vis[tx][ty]) { next.x=tx; next.y=ty; next.pos=now.pos+1; vis[tx][ty]=1; a.push(next); } } } } } int main() { while(cin>>s>>e) { sx=s[0]-'a'+1; sy=s[1]-'0'; ex=e[0]-'a'+1; ey=e[1]-'0'; cout<<"To get from "<<s<<" to "<<e<<" takes "<<dfs()<<" knight moves."<<endl; } return 0; }
HDU 1372——DFS
最新推荐文章于 2021-08-10 15:14:53 发布