题目:http://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1639
心得:用bfs来做,一开始弄成分情况讨论了。
#include<bits/stdc++.h>
using namespace std;
int fx[8][2]={{1,1},{1,0},{1,-1},{0,1},{0,-1},{-1,1},{-1,0},{-1,-1}};
int vis[10][10];
int r1,c1,r2,c2,r3,c3;
struct Node{
int x,y;
int step;
};
int check(Node a)
{
if(a.x<1||a.y<1||a.x>8||a.y>8)
return 1;
if(vis[a.x][a.y]) return 1;
if(a.x==r3&&a.y==c3) return 1;
return 0;
}
int bfs()
{
Node st,ed;
st.x=r1;
st.y=c1;
st.step=0;
queue <Node> q;
q.push(st);
while(!q.empty())
{
st=q.front();
q.pop();
if(st.x==r2&&st.y==c2) return st.step;
for(int i=0;i<8;i++)
{
ed.x=st.x+fx[i][0];
ed.y=st.y+fx[i][1];
if(check(ed)) continue;
ed.step=st.step+1;
vis[ed.x][ed.y]=1;
q.push(ed);
}
}
}
int main(void)
{
int pt=1;
while(~scanf("%d%d%d%d%d%d",&r1,&c1,&r2,&c2,&r3,&c3))
{
memset(vis,0,sizeof(vis));
vis[r1][c1]=0;
int re=bfs();
printf("Case %d: %d\n",pt++,re);
}
return 0;
}