In "exploreComponent" function count is increasing according to the no. of nodes present in that Component but before returning count decreases to 1, why this happening ?
Defined a Graph using matrix representation. Nodes are representated as nVertices. Firstly I made all the connection of nodes as 0 after adding edge between two nodes it is represented as 1 in adjMatrix.
class Graph:
def __init__(self,nVertices):
self.nVertices = nVertices
self.adjMatrix = [[0 for i in range(nVertices)] for j in range(nVertices)]
def addEdge(self,v1,v2):
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
def containsEdge(self,v1,v2):
return True if self.adjMatrix[v1][v2] > 0 else False
def removeEdge(self,v1,v2):
if self.containsEdge(v1,v2) is False:
return
self.adjMatrix[v1][v2] = 0
self.adjMatrix[v2][v1] = 0
*# largest compenent*
def largestComponent(self):
visited = [False for i in range(self.nVertices)]
largest = 0
for i in range(self.nVertices):
if visited[i] is False:
count = 0
countNode = self.exploreComponent(i,visited,count)
largest = max(countNode,largest)
return largest
*#helper function*
def exploreComponent(self,node,visited,count):
visited[node] = True
count += 1
print(count)
for j in range(self.nVertices):
if self.adjMatrix[node][j] > 0 and visited[j] is False:
self.exploreComponent(j,visited,count)
print("res",count)
return count
*# creating graph*
g = Graph(9)
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,3)
g.addEdge(4,5)
g.addEdge(6,7)
g.addEdge(7,8)
*# Function Calling*
res = g.largestComponent()
print(res)
Result:
1
2
3
4
res 4
res 3
res 2
res 1
1
2
res 2
res 1
1
2
3
res 3
res 2
res 1
1
The method exploreComponent is returning the incremented value of count. However when you invoke it, you are not storing the returned value anywhere
self.exploreComponent(j,visited,count)
( BTW you need to fix your question tags. Add the language ( python? ) and remove 'graph' since this is actually a question about graph theory )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.