广度优先遍历:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner; class Node{
public int x_,y_;
public int time_;
public Node(int x,int y,int t){
x_ = x;
y_ = y;
time_ = t;
}
} public class Main { public static boolean inside(int x,int y,int r,int c){
if(x>=0&&x<r&&y>=0&&y<c)
return true;
return false;
} public static void main(String[] args)
{
Integer[][] graph = new Integer[11][11];
int[][] dir = new int[][]{{-1,0}, {0, 1}, {1, 0},{0,-1}};
boolean[][] flag = new boolean[11][11];
int row=0, col=0,total=0,cnt=0;
Scanner in = new Scanner(System.in);
Queue<Node> que = new LinkedList<Node>();
while(in.hasNext()){
String line = in.nextLine();
if(line.equals(""))
break;
String[] strs = line.split("\\ ");
col = strs.length;
for(int i=0;i<col;i++) {
graph[row][i] = Integer.valueOf(strs[i]);
if(graph[row][i]!=0)
total++;
if(graph[row][i] == 2){
flag[row][i] = true;
Node node = new Node(row,i,0);
que.add(node);
}
}
row++;
}
int res = 0;
while(que.isEmpty() == false){
Node now = que.poll();
res = Math.max(res, now.time_);
cnt++;
//System.out.println(now.x_+now.y_);
for(int i=0;i<4;i++){
int xx = now.x_+dir[i][0];
int yy = now.y_+dir[i][1];
if(inside(xx,yy,row,col)&&flag[xx][yy]==false&&graph[xx][yy]==1){
flag[xx][yy] = true;
que.add(new Node(xx,yy,now.time_+1));
}
}
}
if(cnt<total)
System.out.println(-1);
else if(cnt==total)
System.out.println(res);
return ;
}

最新文章

  1. java异常知识点整理
  2. POJ 2752 - Seek the Name, Seek the Fame (KMP)
  3. Bone.io是一个轻量级的框架构建高性能实时单页HTML5应用程序
  4. 使用C#通过调用minitab的COM库自动化生成报表
  5. HDU5649 DZY Loves Sorting 线段树
  6. Oracle教程-安装、结构(一)
  7. 交互模式下测试python代码及变量的四则运算
  8. Python内置函数(34)——filter
  9. cbp2make使用
  10. java 网络通信传输层协议——UDP和TCP
  11. 保护 .NET Core 项目的敏感信息
  12. 浏览器兼容性汇总--CSS篇
  13. hive SQL 静态分区和 动态分区
  14. 在WINDOWS下安装MYSQL8.0
  15. C++判断是否连接服务器
  16. Css中如何使英文和拼音变成全大写、全小写和首字母大写?
  17. Oracle学习笔记之一,重温范式
  18. PIVOT运算符使用(动态行转列)
  19. Oracle的物理存储与逻辑存储关系对应
  20. 拼接sql语句参数绑定

热门文章

  1. 【JSOI 2014】序列维护
  2. Bootstrap-CSS:排版
  3. 监听屏幕旋转事件window. onorientationchange
  4. centos7命令行模式安装&amp;&amp;配置_br0+kvm+虚拟机+添加硬盘+快照及恢复
  5. 由mysql分区想到的分表分库的方案
  6. Mac下的常用终端命令与vim常用命令
  7. CSA Round #50 (Div. 2 only) Min Swaps(模拟)
  8. .NET Core 跨平台物联网开发:连接阿里云IOT(一)
  9. CH 6021 走廊泼水节
  10. Linux开启SELinux的情况下怎么解决nginx403跟502错误