class Graph:
adj = []
# Function to fill empty adjacency matrix
def __init__(self, v, e):
self.v = v
self.e = e
Graph.adj = [[0 for i in range(v)]
for j in range(v)]
# Function to add an edge to the graph
def addEdge(self, start, e):
# Considering a bidirectional edge
Graph.adj[start][e] = 1
Graph.adj[e][start] = 1
# Function to perform BFS on the graph
def BFS(self, start):
ans = []
# Visited vector to so that a
# vertex is not visited more than
# once Initializing the vector to
# false as no vertex is visited at
# the beginning
visited = [False] * self.v
q = [start]
# Set source as visited
visited[start] = True
while q:
vis = q[0]
# Print current node
ans.append(str(vis))
q.pop(0)
# For every adjacent vertex to
# the current vertex
for i in range(self.v):
if (Graph.adj[vis][i] == 1 and
(not visited[i])):
# Push the adjacent node
# in the queue
q.append(i)
# set
visited[i] = True
return " ".join(ans)
n = int(input())
for i in range(n):
m = int(input())
graf = Graph(m, m)
for j in range(m):
line = input()
for k in range(m):
if line[k] == '1':
graf.addEdge(k, j)
ans = graf.BFS(i)
print(int(ans.split()[0]) + 1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | class Graph: adj = [] # Function to fill empty adjacency matrix def __init__(self, v, e): self.v = v self.e = e Graph.adj = [[0 for i in range(v)] for j in range(v)] # Function to add an edge to the graph def addEdge(self, start, e): # Considering a bidirectional edge Graph.adj[start][e] = 1 Graph.adj[e][start] = 1 # Function to perform BFS on the graph def BFS(self, start): ans = [] # Visited vector to so that a # vertex is not visited more than # once Initializing the vector to # false as no vertex is visited at # the beginning visited = [False] * self.v q = [start] # Set source as visited visited[start] = True while q: vis = q[0] # Print current node ans.append(str(vis)) q.pop(0) # For every adjacent vertex to # the current vertex for i in range(self.v): if (Graph.adj[vis][i] == 1 and (not visited[i])): # Push the adjacent node # in the queue q.append(i) # set visited[i] = True return " ".join(ans) n = int(input()) for i in range(n): m = int(input()) graf = Graph(m, m) for j in range(m): line = input() for k in range(m): if line[k] == '1': graf.addEdge(k, j) ans = graf.BFS(i) print(int(ans.split()[0]) + 1) |
English