2019年今日头条机试_JAVA后台岗_第一题
广度优先遍历:
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 ; }