Given a graph of N nodes, E edges, a node X and a distance K. The task is to print all the nodes within the distance K from X.
Output: 4 5 2 7 3
Neigbour nodes within distance 2 of node 4 are: 4 5 2 7 3
To print all the nodes that are at distance K or less than K. We can do it by applying dfs variation, that takes K node from where we have to print the distance until distance K.
dfs(K, node, -1, tree)
Here -1 indicates node parent.
This recursive function basically prints the node and then calls the dfs(K-1, neighbour of node, node, tree).
Base condition is K>0.
Below is the implementation of the above approach:
4 5 2 7 3
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print nodes at k distance from root
- Print all nodes at distance k from a given node
- Print all nodes at distance K from given node: Iterative Approach
- Minimum nodes to be colored in a Graph such that every node has a colored neighbour
- Count nodes within K-distance from all nodes in a set
- Shortest distance between two nodes in BST
- Find distance between two nodes of a Binary Tree
- Find count of pair of nodes at even distance
- Find the shortest distance between any pair of two different good nodes
- Print levels with odd number of nodes and even number of nodes
- Print all nodes that don't have sibling
- Program to print all the non-reachable nodes | Using BFS
- Print all leaf nodes of an n-ary tree using DFS
- Print the path between any two nodes of a tree | DFS
- Print Nodes in Top View of Binary Tree
- Print all nodes in a binary tree having K leaves
- Print nodes having maximum and minimum degrees
- Print node whose each neighboring Tree has all nodes of same color
- Print Common Nodes in Two Binary Search Trees
- Print leftmost and rightmost nodes of a Binary Tree