T
T
tumur42021-10-05 18:35:18
Python
tumur4, 2021-10-05 18:35:18

Runtime-Error, how to fix?

from collections import defaultdict
import sys
sys.setrecursionlimit(200)
temp = []
n = int(input())
numbers = [input().split() for i in range(int(n))]
for i,j in enumerate(numbers):
    for k, l in enumerate(j):
        if l == '1':
            temp.append([i + 1, k + 1])
graph = defaultdict(list)
for number in temp:
    if number[0] != number[1]:
        graph[int(number[0])].append(number[1])
cycle = False
used = {i: False for i in range(1, n+1)}

Color = [0] * (n + 1)
CycleFound = False
predki = [0] * (n + 1)
cycle = []
p = 0
def dfs(v):
    Color[v] = 1
    cycle.append(v)
    for u in graph[v]:
        if Color[u] == 0:
            predki.insert(u, v)
            dfs(u)
        elif Color[v] == 1 and u != predki[v]:
            global p
            while p < 1:
                global CycleFound
                CycleFound = True
                if v not in graph[cycle[0]]:
                    del cycle[0]
                print('YES')
                print(len(cycle))
                print(' '.join(map(str, cycle)))
                p += 1
    cycle.clear()
    Color[v] = 2

for i in range(1, n + 1):
    if Color[i] == 0:
        dfs(i)
if CycleFound == False:
    print('NO')

IContest gives an error RE.
Input format
The first line contains a single number n — the number of vertices in the graph ( 1 ≤ n ≤ 500 ). Next, n lines contain the graph itself by the adjacency matrix.

Output Format
If there is no cycle in the source graph, then print "NO". Otherwise, on the first line print "YES", on the second line print the number k — the number of vertices in the cycle, and on the third line print k different numbers — the numbers of the vertices that belong to the cycle in the bypass order (the bypass can start from any cycle vertex). If there are several cycles, then print any one.

ERROR:
Traceback (most recent call last):
File "f68a00f8-de32-4961-a41b-d6a89720f012", line 45, in
dfs(i)
File "f68a00f8-de32-4961-a41b-d6a89720f012", line 28, in dfs
dfs(u) File "
f68a00f8-de32-4961-a41b-d6a89720f012", line 28, in dfs line repeated 3 more times] File "f68a00f8-de32-4961-a41b-d6a89720f012", line 34, in dfs if v not in graph[cycle[0]]: IndexError: list index out of range

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question