Graph Node Neighbors
EasyPractice library · +10 XPgraphsadjacency listbfs
You are given a graph represented by its adjacency list. For each node in the graph, print all of its neighbors. The neighbors for each node should be printed in ascending order. Nodes are numbered from 0 to N-1.
Input
The first line contains two integers N and M, the number of nodes and edges respectively. The next M lines each contain two integers u and v, representing an undirected edge between node u and node v.
Output
For each node from 0 to N-1, print a line. The line should start with the node number, followed by a colon and a space, then its neighbors in ascending order, separated by spaces. If a node has no neighbors, print its number followed by a colon and a space, with nothing after.
Constraints
1 <= N <= 1000, 0 <= M <= 10000, 0 <= u, v < N, u != v
Time limit 1 s (native code; slower languages get more)Memory 256 MB9 hidden tests
Example 1
Input
4 3 0 1 0 2 1 2
Output
0: 1 2 1: 0 2 2: 0 1 3:
Example 2
Input
3 0
Output
0: 1: 2:
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
4 3 0 1 0 2 1 2
Example 2 input
3 0