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.
- Multistage Graph (Shortest Path)
- Some interesting shortest path questions | Set 1
- Shortest path in a Binary Maze
- Shortest path in an unweighted graph
- Dijkstra’s shortest path algorithm using set in STL
- Shortest Path using Meet In The Middle
- Dijkstra's Shortest Path Algorithm using priority_queue of STL
- Dijkstra's shortest path with minimum edges
- Shortest Path in Directed Acyclic Graph
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Multi Source Shortest Path in Unweighted Graph
- Dijkstra's shortest path algorithm in Java using PriorityQueue
- Find shortest safe route in a path with landmines
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Printing Paths in Dijkstra's Shortest Path Algorithm
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.