0

I try to solve this problem, but my code returns a runtime error.
I tried with many changes, but I don't know where returns runtime error exactly.
I need some advice or some special cases please...

graph = {}
visited = None

not_visited_vertex = -1
visited_vertex = 1

def dfs(u):
    stack = [u]

    while stack:
        this = stack.pop()
        if visited[this] == not_visited_vertex:
            visited[this] = visited_vertex
            print(this, end=' ')

            for i in sorted(graph[this], reverse=True):
                if visited[i] == not_visited_vertex:
                    stack.append(i)

def bfs(u):
    from collections import deque
    q = deque()
    q.appendleft(u)

    while q:
        this = q.pop()
        visited[this] = visited_vertex
        print(this, end=' ')

        for i in sorted(graph[this]):
            if visited[i] == not_visited_vertex:
                visited[i] = visited_vertex
                q.appendleft(i)


if __name__ == "__main__":
    import sys
    n, m, v = map(int, sys.stdin.readline().rstrip().split())

    for i in range(m):
        v1, v2 = map(int, sys.stdin.readline().split())
        if v1 not in graph:
            graph[v1] = []
        graph[v1].append(v2)
        if v2 not in graph:
            graph[v2] = []
        graph[v2].append(v1)

    visited = [not_visited_vertex for _ in range(n+1)]
    dfs(v)

    print()
    visited = [not_visited_vertex for _ in range(n+1)]
    bfs(v)
c0der
  • 18,467
  • 6
  • 33
  • 65
  • Are you executing the script from a console or from an IDE? In either case the exception thrown should be written to the console, with a stack trace. This will tell you the line of code that caused the problem. – ds4940 Jan 15 '20 at 09:46
  • There is no error with given test cases in my local. But error thrown from that site's system.. – Steven Shin Jan 15 '20 at 09:58
  • May I suggest adding some logging and exception handling. If you just wrap everything under __name__ in a try except block, then in the except part, catch the exception and write it to a log file. This should give you stack trace and the type of exception thrown. To test this functionality, just put something like [][1] (an Index Error) anywhere in your script – ds4940 Jan 15 '20 at 11:00
  • @ds4940 I'll try this, thank you! – Steven Shin Jan 15 '20 at 13:35

0 Answers0