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;
        }
    }
  • 相关阅读:
    嵌入式软件开发环境搭建与工具推荐
    软件常用设计原则与实践:契约式接口设计、安全编码实践
    服务器崩掉 ,只剩下挂载文件,重现github docker 容器
    基础巩固篇 —— CountDownLatch的理解
    基础巩固篇 —— 对锁的理解
    基础巩固篇 —— 对不安全集合的理解
    基础巩固篇 —— 对CAS的理解
    基础巩固篇 —— 对volatile关键字的理解
    响应式布局
    jQuery Mobile 网格
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9677591.html
Copyright © 2011-2022 走看看