能否跳完N个格子

题目:

地上共有N个格子,你需要跳完地上所以的格子,但是格子间是有强依赖关系的,跳完前一个格子后,后续的格子才会被开启,给质检的依赖关系由多组steps数组给出,steps[0]表示前一个格子,steps[1]表示steps[0]可以开启的格子:比如[0,1]表示从跳完第0个格子以后第一个格子就开启了,再比如[2,1],[2,3]表示跳完第2个格子后第1个格子和第3个格子就被开启了。请计算能够否由给出的steps数组跳完所有的格子,如果可以输出yes,否则输出no。

说明:1,你可以从一个格子跳到任意一个开启的格子;2,没有前置依赖条件的格子默认就是开启的;3,如果总数是N,则所有格子编号为[0,N-1]连续数组。输入为一个数组N表示总共有多少格子,接着输入多组二维数组steps表示所有格子之间的依赖关系;输出为,如果能按照steps给出的依赖关系跳完所有格子,输出yes,否则输出no。

示例1:

输入:

3

[0,1]

[0,2]

输出:

yes

示例2:

输入:

2

[1,0]

[0,1]

输出:

no

示例3:

输入:

6

[0,1]

[0,2]

[0,3]

[0,4]

[0,5]

输出:

yes

 public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.nextLine();
        List<List<Integer>> grip = new LinkedList<>();

        while (true) {
            String line = scan.nextLine();
            List<Integer> relation = new LinkedList<>();
            // 如果当前行为空
            if (line.isEmpty()) {
                break;   //遇空行,停止输入
            } else {
                // 非空行,添加到输入列表
                String[] temp = line.split(" ");
                relation.add(Integer.parseInt(temp[0]));
                relation.add(Integer.parseInt(temp[1]));
                grip.add(relation);
            }
        }
        
        
        String result = gripJump(grip,n);
        System.out.println(result);
    }

    private static String gripJump(List<List<Integer>> grip, int n) {
        Map<Integer,List<Integer>> map = new HashMap<>();
        for(int i=0;i< n;i++){
            map.put(i,new LinkedList<>());
        }
        for(List<Integer> relation : grip){
            map.get(relation.get(0)).add(relation.get(1));
        }
        Queue<Integer> initGrip = new LinkedList<>();
        for(int i =0;i< n;i++){
            initGrip.add(i);
        }
        for(List<Integer> relation : grip){
            initGrip.remove(relation.get(1));
        }
        List<Integer> countGripJump = new LinkedList<>();
        while(!initGrip.isEmpty()){
            int current = initGrip.poll();
            countGripJump.add(current);
            initGrip.addAll(map.get(current));


        }
        return countGripJump.size()== n?"yes":"no";
    }

#笔试##技术岗笔试题求解#
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务