题目描述
印刷电路板将布线区域划分成 n×m 个方格阵列,要求确定连接方格阵列中的方格a 点到方格b 的最短布线方案。在布线时,电路只能沿直线布线,为了避免线路相交,已布了线的方格做了封锁标记,其他线路不允许穿过被封锁的方格。问线路至少穿过几个方格。
输入格式
输入的第一行是两个整数 n 和m(2<=n<=100,2<=m<=100),表示阵列的范围,以及被封锁的方格。接下来有k 行,每行两个整数x 和y。表示被封锁的方格(1<=x<=n,1<=y<=m)。再接下来是四个整数x1 , y1 , x2 , y2 表示起点a 的坐标和起点b 的坐标。
输出格式
输出最短的布线方案的长度,若不存在,则输出-1。
样例输入content_copy
7 7 14
1 3
2 3
2 4
3 5
4 4
4 5
5 1
5 5
6 1
6 2
6 3
7 1
7 2
7 3
3 2 4 6
样例输出content_copy
10
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class point {
int x;int y;
int result;
point (int x,int y,int result){
this.x=x;
this.y=y;
this.result=result;
}
}
public class Main {
static int[] up= {1,0,-1,0};
static int[] down= {0,1,0,-1};
static Queue<point> queue=new LinkedList<point>();
static int n;
static int m;
static boolean flag=false;
static void print(int[][] map,int n,int m) {
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
System.out.print(map[i][j]+" ");
}System.out.println();
}
}
public static void main(String[] args) {
Scanner se=new Scanner(System.in);
n=se.nextInt();
m=se.nextInt();
int[][] map=new int[n+1][m+1];
int num=se.nextInt();
for(int i=0;i<num;i++) {
int x=se.nextInt();
int y=se.nextInt();
map[x][y]=1;
}
int startX=se.nextInt();
int startY=se.nextInt();
int endX=se.nextInt();
int endY=se.nextInt();
map[endX][endY]=-1;
queue.add(new point(startX,startY,1));
//print(map,n,m);
while(!queue.isEmpty()&&flag==false)
bfs(map);
}
private static void bfs(int[][] map) {
if(flag==false) {
point p=queue.poll();
int x=p.x;
int y=p.y;
int result=p.result;
if(x<1||x>n||y<1||y>m)return;//边界值
if(map[x][y]==1) return;//障碍
if(map[x][y]==3) return;//走过
if(map[x][y]==-1) {//找到
System.out.println(p.result);
flag=true;
return;
}
//System.out.println(x+" "+y+" "+result);
map[x][y]=3;
for(int i=0;i<4;i++) {//搜索
x+=up[i];
y+=down[i];
queue.add(new point(x,y,result+1));
x-=up[i];
y-=down[i];
}
}else return;
}
}