C
C#2mo ago
daniel2

Graph structure problem, is my code correct?

given a directed graph contain groups of nodes, a node in the graph can't access all the node in the graph. Each node will only point to one node or nothing (null), return the number of groups in this graph.
1 Reply
daniel2
daniel22mo ago
Node[] nodes = new Node[10];
HashSet<Node> visited = new HashSet<Node>();
int count = 0;
for (int i = 0; i < nodes.Length; i++)
{
Node current = nodes[i];
if (visited.Contains(current)) continue;
while (current != null)
{
visited.Add(current);
current = current.Next;
if (visited.Contains(current) || current == null)
{
count++;
break;
}
}
}
Node[] nodes = new Node[10];
HashSet<Node> visited = new HashSet<Node>();
int count = 0;
for (int i = 0; i < nodes.Length; i++)
{
Node current = nodes[i];
if (visited.Contains(current)) continue;
while (current != null)
{
visited.Add(current);
current = current.Next;
if (visited.Contains(current) || current == null)
{
count++;
break;
}
}
}
The array stores all node in the graph