1. 程式人生 > >LC 841. Keys and Rooms

LC 841. Keys and Rooms

1.題目

841. Keys and Rooms

Medium

31524

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.

2.解題思路

題目大意是說有若干房間,一開始除了0號房間都是鎖著的。每個房間裡有若干鑰匙,可以開啟其他房間的門。問最後可不可以開啟所有房間。

實際上鑰匙就相當於邊,題目就是問給一個圖,能不能訪問所有的結點。用DFS或者BFS都可以,這裡用了BFS,用一個visited陣列記錄頂點的訪問情況。最後如果所有頂點都訪問過則返回true,否則false。

3.程式碼

class Solution {
public:
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
        int num = rooms.size();
        int visited[num];
        memset(visited, 0, sizeof(visited));
        queue<int> Q;
        Q.push(0);
        visited[0]=1;
        while(!Q.empty()) {
            for (auto n:rooms[Q.front()]) {
                if (visited[n]==0) {
                Q.push(n);
                visited[n]=1;
                }
            }
            Q.pop();
        }
        for (int i=0; i<num; i++) {
            if(visited[i]==0) return false;
        }
        return true;
    }
};