[英]Connected components std::pair<std::int, std::int> how to
I have a pair representation std::pair<std::int,std::int>
of an adjacency list like so:我有一个邻接列表的对表示
std::pair<std::int,std::int>
,如下所示:
(0,0)
(0,3)
(1,0)
(1,1)
(2,3)
(3,0)
(3,1)
(3,2)
(3,3)
(so node 0 is connected to nodes 0 and 3, node 1 is connected to nodes 0 and 1, and so forth). (因此节点 0 连接到节点 0 和 3,节点 1 连接到节点 0 和 1,依此类推)。
What is the smartest way to find connected components with this representation?用这种表示法找到连接组件的最聪明的方法是什么?
I'm not supposed to change the input, so converting it to a matrix (for example) and running DFS on it is not an option.我不应该更改输入,因此将其转换为矩阵(例如)并在其上运行 DFS不是一种选择。
How do I best approach this?我如何最好地解决这个问题?
Thanks all (particularly BessieTheCow for pointing out the disjoint-set data structure).谢谢大家(特别是BessieTheCow指出了不相交的数据结构)。
In the end, it turned out to be just an ordinary DFS:最后,原来只是一个普通的 DFS:
typedef std::unordered_set<std::pair<int,int>, Pairhash> adjacencySet;
//Needed for unordered_set
struct Pairhash {
public:
template <typename T, typename U>
std::size_t operator()(const std::pair<T, U> &x) const
{
return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
}
};
void dfs(std::shared_ptr<adjacencySet> visited, const std::pair<int, int> &pair, const adjacencySet &adjacencies)
{
if (visited->find(pair) != visited->end())
{
return;
}
visited->emplace(pair);
std::pair<int,int> temp;
if (pair.first > 0)
{
temp = std::make_pair(pair.first -1, pair.second); //Look up
if (adjacencies.find(temp) != adjacencies.end())
{
dfs(visited, temp, adjacencies);
}
}
if (pair.second > 0)
{
temp = std::make_pair(pair.first, pair.second-1); //Look left
if (adjacencies.find(temp) != adjacencies.end())
{
dfs(visited, temp, adjacencies);
}
}
temp = std::make_pair(pair.first +1, pair.second); //Look down
if (adjacencies.find(temp) != adjacencies.end())
{
dfs(visited, temp, adjacencies);
}
temp = std::make_pair(pair.first, pair.second +1); //Look right
if (adjacencies.find(temp) != adjacencies.end())
{
dfs(visited, temp, adjacencies);
}
}
int countComponents(const adjacencySet &adjacencies)
{
std::shared_ptr<adjacencySet> visited = std::make_shared<adjacencySet>(adjacencies.size());
auto count(0);
for (auto pair : adjacencies)
{
if (visited->find(pair) == visited->end())
{
dfs(visited, pair, adjacencies);
count += 1;
}
}
return count;
}
With an example set like so:使用这样的示例集:
(0,0)
(0,3)
(1,0)
(1,1)
(2,3)
(3,0)
(3,1)
(3,2)
(3,3)
(this would be represented as (这将表示为
{1,0,0,1}
{1,1,0,0}
{0,0,0,1}
{1,1,1,1}
in a matrix representation).在矩阵表示中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.