LeetCode 1245. 树的直径(图的最大直径结论)

文章目录

1. 题目

2. 解题

  • 结论:求无权无向图中的最长一条路径
    先从任意一点P出发,找到离它最远的点Q
    再从点Q出发,找离它最远的点W,W到Q的距离就是最长的一条路

  • 采用2次BFS遍历

class Solution {
public:
    int treeDiameter(vector<vector<int>>& edges) {
    	int n = edges.size()+1;
    	unordered_map<int,unordered_map<int,bool>> m;
    	for(auto& e : edges)
    	{
    		m[e[0]][e[1]] = 1;
    		m[e[1]][e[0]] = 1;
    	}
    	int a,cur,size,step = 0;
    	queue<int> q;
    	vector<bool> visited(n,false);
    	q.push(0);
    	visited[0] = true;
    	while(!q.empty())
    	{
			cur = q.front();
			q.pop();
			a = cur;//记录最后到达的点a
			for(auto it = m[cur].begin(); it != m[cur].end(); ++it)
			{
				if(!visited[it->first])
				{
					q.push(it->first);
					visited[it->first] = true;
				}
			}
    	}
    	vector<bool> visited1(n,false);
    	q.push(a);//从a出发,到达的最远的就是最大的路径
    	visited1[a] = true;
    	while(!q.empty())
    	{
    		size = q.size();
    		while(size--)
    		{
    			cur = q.front();
    			q.pop();
				for(auto it = m[cur].begin(); it != m[cur].end(); ++it)
                {
                    if(!visited1[it->first])
                    {
                        q.push(it->first);
                        visited1[it->first] = true;
                    }
                }
    		}
    		step++;
    	}
    	return step-1;
    }
};

136 ms 24.4 MB


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章