0
def isCyclicUtil(graph,v,visit,parent): 
    visit[v]= True
    for i in graph[v]: 
        if  visit[i]==False :  
            if(isCyclicUtil(graph,i,visit,v)): 
                 return True
            elif  parent!=i: 
                 return True

    return False


def isCyclic(graph,n): 
    visited =[False]*(n) 
    for i in range(n):
        print(visited,i)
        if visited[i] == False:
            if(isCyclicUtil(graph,i,visited,-1)) == True: 
                return True


    return False



print(isCyclic({0: [1], 1: [0], 2: [3, 4], 3: [2, 4], 4: [3, 2]},5))

At each iteration visited array is updated

OUTPUT:
index : 0    visited array :  [False, False, False, False, False]
index : 1    visited array :  [True, True, False, False, False]
index : 2    visited array :  [True, True, False, False, False]

In the above code, values of visited array are being changed without any explicit modification to the visited array. what is the reason behind this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
dave
  • 19
  • 5
  • What do you mean by *"without any explicit modification to the visited array"*? You do `visit[v] = True`, that's what updated the list. – a_guest Jun 15 '20 at 20:45
  • `visit[v]= True` is an explicit modification, no? BTW welcome to SO! Check out the [tour] and [ask] if you want advice. – wjandrea Jun 15 '20 at 20:45
  • The `return False` in your first function is not indented correctly. Is it supposed to be inside the for loop or outside of it? – khelwood Jun 15 '20 at 20:46
  • @a_guest, is list being passed as a reference and not a copy? – dave Jun 15 '20 at 20:47
  • @dave Python is neither pass by value nor pass by reference. All you do is bind names to objects. If these objects can be modified or not depends on whether they are *mutable* or *immutable*. When you do `visited = [False] * n`, this creates a list object in memory and binds the name `visited` to it (i.e. whenever you use that name you reference that very object). Then when you call `isCyclicUtil(graph, i, visited, -1)`, it binds the parameter name `visit` to the corresponding argument `visited`. Now both names refer to the very same object. Since a list is mutable all changes are reflected. – a_guest Jun 16 '20 at 09:01
  • @a_guest Thank you! I understand it now. – dave Jun 16 '20 at 12:04

0 Answers0