poj-1915

没什么好说的
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;
					 
				 }
			 }
			 
		 }
	 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值