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;
        }
    }
  • 相关阅读:
    给asterisk写app供CLI调用
    C++实现raw_input
    CentOS6下配置本地用户访问vsftpd,并赋予写权限
    用SqlServer存储Asterisk的呼叫记录
    go 1发布了,之前写的代码不能运行了
    字符串分割(C++)
    asterisk事件监控
    git的简单使用
    用Python访问SqlServer
    像Python那样跑go1的代码(Windows下双击运行)
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9677591.html
Copyright © 2011-2022 走看看