1. 程式人生 > 其它 >刷題-力扣-LCP 07. 傳遞資訊

刷題-力扣-LCP 07. 傳遞資訊

LCP 07. 傳遞資訊

題目連結

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/chuan-di-xin-xi
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

題目描述

小朋友 A 在和 ta 的小夥伴們玩傳資訊遊戲,遊戲規則如下:

有 n 名玩家,所有玩家編號分別為 0 ~ n-1,其中小朋友 A 的編號為 0
每個玩家都有固定的若干個可傳資訊的其他玩家(也可能沒有)。傳資訊的關係是單向的(比如 A 可以向 B 傳資訊,但 B 不能向 A 傳資訊)。
每輪資訊必須需要傳遞給另一個人,且資訊可重複經過同一個人
給定總玩家數 n,以及按 [玩家編號,對應可傳遞玩家編號] 關係組成的二維陣列 relation。返回資訊從小 A (編號 0 ) 經過 k 輪傳遞到編號為 n-1 的小夥伴處的方案數;若不能到達,返回 0。

示例 1:

輸入:n = 5, relation = [[0,2],[2,1],[3,4],[2,3],[1,4],[2,0],[0,4]], k = 3

輸出:3

解釋:資訊從小 A 編號 0 處開始,經 3 輪傳遞,到達編號 4。共有 3 種方案,分別是 0->2->0->4, 0->2->1->4, 0->2->3->4。

示例 2:

輸入:n = 3, relation = [[0,2],[2,1]], k = 2

輸出:0

解釋:資訊不能從小 A 處經過 2 輪傳遞到編號 2

限制:

  • 2 <= n <= 10
  • 1 <= k <= 5
  • 1 <= relation.length <= 90, 且 relation[i].length == 2
  • 0 <= relation[i][0],relation[i][1] < n 且 relation[i][0] != relation[i][1]

題目分許

  1. 根據題目描述,計算通過k次傳遞將資訊從0傳遞到n-1的總路徑
  2. 廣度優先搜尋k次,在低k次搜尋中n-1出現的次數,即為所求

程式碼

class Solution {
public:
    int numWays(int n, vector<vector<int>>& relation, int k) {
        queue<int> nodeQue;
        nodeQue.push(0);
        int nodeQueLen;
        int sum = 0;
        while (k--) {
            nodeQueLen = nodeQue.size();
            while (nodeQueLen--) {
                for (auto r : relation) {
                    if (r[0] == nodeQue.front()) nodeQue.push(r[1]);
                }
                nodeQue.pop();
            }
        }
        while (!nodeQue.empty()) {
            if (nodeQue.front() == n - 1) ++sum;
            nodeQue.pop();
        }
        return sum;
    }
};