LintCode 178-圖是否是樹

分析

  • 判斷邊總數(shù)是否為n-1;
  • 判斷一次dfs是否能訪問所有節(jié)點。
class Solution {
public:
    /**
     * @param n an integer
     * @param edges a list of undirected edges
     * @return true if it's a valid tree, or false
     */
    bool validTree(int n, vector<vector<int>>& edges) {
        // Write your code here
        if (edges.size() != n - 1) return false;
        vector<vector<int>> map(n, vector<int>(n, 0));
        for (int i = 0; i < edges.size(); ++i) {
            int p1 = edges[i][0], p2 = edges[i][1];
            map[p1][p2] = map[p2][p1] = 1;
        }
        vector<bool> visited(n, false);
        dfs(map, 0, visited);
        for (int i = 0; i < visited.size(); ++i) {
            if (!visited[i]) return false;
        }
        return true;
    }
    
    void dfs(vector<vector<int>> &map, int curr, vector<bool> &visited) {
        visited[curr] = true;
        for (int i = 0; i < map[curr].size(); ++i) {
            if (map[curr][i] && !visited[i]) {
                dfs(map, i, visited);
            }
        }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容