zoukankan      html  css  js  c++  java
  • [LeetCode] 841. Keys and Rooms


    There are N rooms and you start in room 0.  Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. 

    Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length.  A key rooms[i][j] = v opens the room with number v.

    Initially, all the rooms start locked (except for room 0). 

    You can walk back and forth between rooms freely.

    Return true if and only if you can enter every room.

    Example 1:

    Input: [[1],[2],[3],[]]
    Output: true
    Explanation:  
    We start in room 0, and pick up key 1.
    We then go to room 1, and pick up key 2.
    We then go to room 2, and pick up key 3.
    We then go to room 3.  Since we were able to go to every room, we return true.
    

    Example 2:

    Input: [[1,3],[3,0,1],[2],[0]]
    Output: false
    Explanation: We can't enter the room with number 2.
    

    Note:

    1. 1 <= rooms.length <= 1000
    2. 0 <= rooms[i].length <= 1000
    3. The number of keys in all rooms combined is at most 3000.

    题意:给一个二维数组,arr[][],arr[] 包含有“钥匙”,找寻下一个“房间”,例如arr[0] = {1,2} 那么你就会获得1,2门的钥匙,也就是说你可以访问1,2,

               问,能不能访问完所有的“房子”

    题不难,一步一步递归回溯就行了,用一个数组去标记是否访问,最后判断是否访问完就行

    class Solution {
        private boolean[] visited;
        private void newCanVAR(List<List<Integer>> rooms, int index) {
            // if(visited[index])
            //     return;
            for (int i = 0; i < rooms.get(index).size(); i++) {
                if (!visited[rooms.get(index).get(i)]) {
                    visited[rooms.get(index).get(i)] = true;
                    newCanVAR(rooms, rooms.get(index).get(i));
                }
            }
            return;
            
        }
        public boolean canVisitAllRooms(List<List<Integer>> rooms) {
            visited = new boolean [rooms.size()];
            visited[0] = true;
            newCanVAR(rooms, 0);
            for (boolean bl : visited) {
                if(!bl)
                    return false;
            }
            return true;
        }
    }
  • 相关阅读:
    java 多线程 Future callable
    nginx Access-Control-Allow-Origin css跨域
    maven 项目调试本地代码
    tomcat -ROOT 与webapps 的关系,关于部署的一些问题
    需求分析,挖掘背后的原因
    js 短信验证码 计时器
    总结一些小问题
    基于synchronized 或 ReadWriteLock实现 简单缓存机制
    java cookie 工具类
    309. 最佳买卖股票时机含冷冻期
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9677591.html
Copyright © 2011-2022 走看看