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 ;
    }

 

转载于:https://www.cnblogs.com/jasonlixuetao/p/10705655.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值