没什么好说的
bfs板子题
import java.util.Queue;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
public class Main {
int m,n,sum,a,b,L;
int[][] vis = new int[350][350]; //标记地图
int[][] map = new int[350][350]; //棋盘
int[][] dir = new int[][]{{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}}; //8个方向
Queue<BI> queue = new ArrayBlockingQueue<BI>(100000); //记录走的点
class BI{
int x;
int y;
int top;
public BI(int x,int y,int top)
{
this.x = x;
this.y = y;
this.top = top;
}
}
public static void main(String[] args) {
Main s = new Main();
Scanner cin = new Scanner(System.in);
int k = cin.nextInt();
while(k>0)
{
k--;
s.sum=0; //步数
s.init(); //初始化vis和queue
s.L = cin.nextInt(); //棋盘的长度
s.a = cin.nextInt();
s.b = cin.nextInt(); //起点
s.m = cin.nextInt();
s.n = cin.nextInt(); //终点
s.bfs(s.a,s.b,0);
System.out.println(s.sum);
}
}
public void init() //初始化
{
for(int i=0;i<vis.length;i++)
{
for(int j=0;j<vis.length;j++)
{
vis[i][j]=0;
}
}
queue.clear();
}
public boolean Check(int x,int y) //判断点是否合理
{
if(x>=0 && x<=L-1 && y>=0 && y<=L-1) //判断点是否超出范围
{
if(vis[x][y]==0) //判断该点是否被走过
{
return true;
}
}
return false;
}
public void bfs(int x,int y,int top)
{
queue.add(new BI(x, y,top)); //把起始点入队
vis[x][y]=1;
while(!queue.isEmpty())
{
BI bi = queue.poll();
if(bi.x==m && bi.y==n) //判断该点是否为终点
{
sum = bi.top;
break;
}
for(int i=0;i<8;i++) //可选择的8个方向
{
int u = bi.x+dir[i][0];
int v = bi.y+dir[i][1]; //下一步要走的点
if(Check(u,v)) //判断该点是否可以走
{
queue.add(new BI(u, v,bi.top+1));
vis[u][v]=1;
}
}
}
}
}