Leetcode841答案与解析 - Keys and Rooms(cpp)

原题

Leetcode原题传送门

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.

解析

这道题思路用动态规划思想做就行了,比较特别的是有个全局的状态:已经进过的房间,不需要回溯。其实就是个简单的迭代。有思维定势的老哥可能会进入圈套。

算法思路:

全局变量:已经打开的房间的集合S

function 进入房间(当前所在房间):

  1. 将当前房间放入S
  2. for(to_房间=所有可以进入的房间): 进入房间(to_房间)

主程序:

  1. 进入房间(房间0)
  2. 如果已经打开的房间的集合S.size()=房间数量 则成功,否则失败

算法复杂度:$$O(nm)$$, n为房间数量,m为每个房间平均对应几把钥匙

因为每进入一个房间,都要判断房间里要是对应的其他房间是否访问过,而由于unordered_set实则是个hash table, 复杂度为O(1)。所以平均下来T(n)=O(n)*O(m)*O(1)=O(nm)

运行速度

没事多刷了几趟,是能刷到100%的

运行速度:4ms | 超过100%的cpp程序

答案

void enterRoom(int roomId, vector< vector<int> >& rooms, unordered_set<int>& enteredRooms) {
    enteredRooms.insert(roomId);
    for (int i = 0; i < rooms[roomId].size(); ++i) {
        int key = rooms[roomId][i];
        if (enteredRooms.find(key) == enteredRooms.end())
            enterRoom(key, rooms, enteredRooms);
    }
}

class Solution {
public:
    bool canVisitAllRooms(vector< vector<int> >& rooms) {
        unordered_set<int> enteredRooms = unordered_set<int>();
        enterRoom(0, rooms, enteredRooms);
        return enteredRooms.size() == rooms.size();
    }
};

注意编译采用-std=c++11 或这支持undoered_set的版本。本地运行请

#include <iostream>
#include <vector>
#include <unordered_set>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值