
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check given graph is a set of trees or not in Python
Suppose we have a graph, represented as a list of edges. We have to check whether the graph is a collection of trees (forest) or not.
So, if the input is like
then the output will be True
To solve this, we will follow these steps −
Define a function dfs() . This will take node, prev
if node in seen, then
return False
insert node into seen
for each adjacent node n in e[node], do
if n is not same as prev, then
if dfs(n, node) is false, then
return False
return True
From the main method, do the following −
e := an empty map
for each start node u and end node v in edges, do
insert v at the end of e[u]
insert u at the end of e[v]
seen := a new set
for each node in e, do
if node is not seen and dfs(node, -1) is false, then
return False
return True
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict class Solution: def solve(self, edges): e = defaultdict(list) for t,f in edges: e[t].append(f) e[f].append(t) seen = set() def dfs(node, prev): if node in seen: return False seen.add(node) for adj in e[node]: if adj != prev: if not dfs(adj, node): return False return True for node in e: if node not in seen and not dfs(node, -1): return False return True ob = Solution() edges = [[0, 1],[0, 2],[4, 3]] print(ob.solve(edges))
Input
[[0, 1],[0, 2],[4, 3]]
Output
True
- Related Questions & Answers
- Program to check whether given graph is bipartite or not in Python
- Check if a given graph is tree or not
- Check if a given tree graph is linear or not in C++
- Program to check given string is pangram or not in Python
- Python program to check whether a given string is Heterogram or not
- Python program to check if a given string is Keyword or not
- Program to check whether odd length cycle is in a graph or not in Python
- Program to check given string is anagram of palindromic or not in Python
- C++ Program to Check Whether a Graph is Strongly Connected or Not
- C++ Program to Check if a Given Graph must Contain Hamiltonian Cycle or Not
- Program to check there is any common reachable node in a graph or not in Python
- Program to check given point in inside or boundary of given polygon or not in python
- Program to check whether given matrix is Toeplitz Matrix or not in Python
- Program to check whether given number is Narcissistic number or not in Python
- Program to check whether given tree is symmetric tree or not in Python