Given two four digit prime numbers, suppose 1033 and 8179, we need to find the shortest path from 1033 to 8179 by altering only single digit at a time such that every number that we get after changing a digit is prime. For example a solution is 1033, 1733, 3733, 3739, 3779, 8779, 8179
Input : 1033 8179 Output :6 Input : 1373 8017 Output : 7 Input : 1033 1033 Output : 0
The question can be solved by BFS and it is a pretty interesting to solve as a starting problem for beginners. We first find out all 4 digit prime numbers till 9999 using technique of Sieve of Eratosthenes. And then using those numbers formed the graph using adjacency list. After forming the adjacency list, we used simple BFS to solve the problem.
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.
- D'Esopo-Pape Algorithm : Single Source Shortest Path
- Single source shortest path between two cities
- Maximize shortest path between given vertices by adding a single edge
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Check if number can be made prime by deleting a single digit
- Number of shortest paths to reach every cell from bottom-left cell in the grid
- Print all possible shortest chains to reach a target word
- Word Ladder (Length of shortest chain to reach a target word)
- Find all numbers between range L to R such that sum of digit and sum of square of digit is prime
- Min steps to convert N-digit prime number into another by replacing a digit in each step
- Minimum number of reversals to reach node 0 from every other node
- Dijkstra's shortest path algorithm | Greedy Algo-7
- Shortest Path in Directed Acyclic Graph
- Some interesting shortest path questions | Set 1
- Shortest path with exactly k edges in a directed and weighted graph
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Printing Paths in Dijkstra's Shortest Path Algorithm
- Dijkstra’s shortest path algorithm using set in STL
- Dijkstra's Shortest Path Algorithm using priority_queue of STL
- Print shortest path to print a string on screen
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.