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.
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Find all numbers between range L to R such that sum of digit and sum of square of digit is prime
- Some interesting shortest path questions | Set 1
- Multistage Graph (Shortest Path)
- Shortest path in a Binary Maze
- Shortest Path using Meet In The Middle
- Shortest path in an unweighted graph
- Dijkstra’s shortest path algorithm using set in STL
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Shortest Path in Directed Acyclic Graph
- Dijkstra's Shortest Path Algorithm using priority_queue of STL
- Dijkstra's shortest path with minimum edges
- Finding sum of digits of a number until sum becomes single digit
- Shortest path with exactly k edges in a directed and weighted graph
- Dijkstra's shortest path algorithm | Greedy Algo-7
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.