现在的位置: 首页 > 综合 > 正文

poj 1915 Knight Moves bfs 用move数组计算第几步好使

2014年01月09日 ⁄ 综合 ⁄ 共 596字 ⁄ 字号 评论关闭

 

#include<iostream>

using namespace std;

#include<queue>

int a1,b1,a2,b2;

int size;

int move[305][305];

int dir[8][2]={-2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2};

void bfs(int x,int y)

{

queue<int> q;

q.push(x);

q.push(y);

while(!q.empty())

{

int m=q.front();q.pop();

int n=q.front();q.pop();

if(m==a2 && n==b2)

break;

for(int i=0;i<8;i++)

{

int mm=m+dir[i][0];

int nn=n+dir[i][1];

if(mm<0||mm>=size||nn<0||nn>=size)

continue;

if(!move[mm][nn])

{

move[mm][nn]=move[m][n]+1;

q.push(mm);

q.push(nn);

}

}

}

}

int main()

{

int x;

cin>>x;

while(x--)

{

cin>>size;

cin>>a1>>b1;

cin>>a2>>b2;

memset(move,0,sizeof(move));

bfs(a1,b1);

cout<<move[a2][b2]<<endl;

}

return 0;

}

 

抱歉!评论已关闭.