zoukankan      html  css  js  c++  java
  • 【LeetCode】841.钥匙和房间(bfs+dfs,java实现)

    题目

    链接

    image-20200715203520676

    题解

    方法一:bfs

    class Solution {
        public boolean canVisitAllRooms(List<List<Integer>> rooms) {
            boolean[] seen = new boolean[rooms.size()];
            seen[0] = true;
            Stack<Integer> stack = new Stack();
            stack.push(0);
    
            //At the beginning, we have a todo list "stack" of keys to use.
            //'seen' represents at some point we have entered this room.
            while (!stack.isEmpty()) { // While we have keys...
                int node = stack.pop(); // Get the next key 'node'
                for (int nei: rooms.get(node)) // For every key in room # 'node'...
                    if (!seen[nei]) { // ...that hasn't been used yet
                        seen[nei] = true; // mark that we've entered the room
                        stack.push(nei); // add the key to the todo list
                    }
            }
    
            for (boolean v: seen)  // if any room hasn't been visited, return false
                if (!v) return false;
            return true;
        }
    }
    

    方法二:dfs

    class Solution {
        public boolean canVisitAllRooms(List<List<Integer>> rooms) {
            boolean[] visit = new boolean[rooms.size()];
            dfs(rooms,0,visit);
            for (boolean visited:visit){
                if (!visited)
                    return false;
            }
            return true;
        }
    
        private void dfs(List<List<Integer>> rooms, int room, boolean[] visit){
            if (!visit[room]){
                visit[room]=true;
                for (int num:rooms.get(room))
                    dfs(rooms,num,visit);
            }
        }
    }
    
  • 相关阅读:
    hbase存储优化
    cloudera manager下phoenix的安装
    Cloudera manager的服务安装以及spark升级到2.2
    redis学习总结
    kylin基础概念和基础性能优化
    mycat使用注意事项
    kylin2.0环境搭建
    ETL实践--kettle转到hive
    集成 SOLR 到 TOMCAT 中(傻瓜教程)
    局域网ip扫描
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13307955.html
Copyright © 2011-2022 走看看