电路布线问题BFS

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
class Node
{
	int var;//是否走得通,访问过即走不通
	int x;
	int y;
	int step=0;//记录步数
	
}

public class Main{
	public static boolean isInmap(int x,int y,int n)
	{
		if(x>=0&&x<n&&y>=0&&y<n)
			return true;
		return false;
	}
public static void main(String[] ab) {
	Scanner sca=new Scanner(System.in);
	int N=sca.nextInt();
	Node[][] map=new Node[N][N];
	for(int i=0;i<N;i++)
		for(int j=0;j<N;j++)
		{
			map[i][j]=new Node();
			map[i][j].x=i;
			map[i][j].y=j;
			map[i][j].var=sca.nextInt();
		}
	LinkedBlockingQueue<Node> q1=new LinkedBlockingQueue();
	int inx=sca.nextInt();
	int iny=sca.nextInt();
	int outx=sca.nextInt();
	int outy=sca.nextInt();
	q1.add(map[inx][iny]);
	map[inx][iny].step=1;
	while(!q1.isEmpty()&&q1.peek()!=map[outx][outy])
	{
		Node pos=q1.poll();
		if(isInmap(pos.x+1,pos.y,N)&&map[pos.x+1][pos.y].var==0)
		{
			q1.add(map[pos.x+1][pos.y]);
			map[pos.x+1][pos.y].step=pos.step+1;
			map[pos.x+1][pos.y].var=1;
		}
		if(isInmap(pos.x,pos.y+1,N)&&map[pos.x][pos.y+1].var==0)
		{
			q1.add(map[pos.x][pos.y+1]);
			map[pos.x][pos.y+1].step=pos.step+1;
			map[pos.x][pos.y+1].var=1;
		}
		if(isInmap(pos.x,pos.y-1,N)&&map[pos.x][pos.y-1].var==0)
		{
			q1.add(map[pos.x][pos.y-1]);
			map[pos.x][pos.y-1].step=pos.step+1;
			map[pos.x][pos.y-1].var=1;
		}
		if(isInmap(pos.x-1,pos.y,N)&&map[pos.x-1][pos.y].var==0)
		{
			q1.add(map[pos.x-1][pos.y]);
			map[pos.x-1][pos.y].step=pos.step+1;
			map[pos.x-1][pos.y].var=1;
		}
		
	}
	if(q1.isEmpty())
		System.out.println("No");
	else
		System.out.println(q1.peek().step);
}

}

bfs一定能找到最优路线

电路布线问题

输入:

7 (行数)
0 0 1 0 0 0 0
0 0 1 1 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 0 0
1 0 0 0 1 0 0 
1 1 1 0 0 0 0
1 1 1 0 0 0 0

2 1 3 5(起点终点)

输出:10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值