forked from Michael-Calce/GeeksForGeeks-Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06 January Shortest Prime Path
42 lines (38 loc) · 1.13 KB
/
06 January Shortest Prime Path
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution{
bool isPrime(string &s) {
int n = stoi(s);
for(int i=2; i<=sqrt(n); i++) {
if(n % i == 0) return false;
}
return true;
}
public:
int shortestPath(int Num1,int Num2) {
string n1 = to_string(Num1), n2 = to_string(Num2);
queue<string> q;
q.push(n1);
int ans = 0;
unordered_set<string> vis;
while(q.size()) {
int n = q.size();
while(n--) {
string temp = q.front();
q.pop();
string prev = temp;
if(prev == n2) return ans;
for(int i=0; i<4; i++) {
for(char c='0'; c<='9'; c++){
temp[i] = c;
if(isPrime(temp) && temp[0] != '0' && vis.find(temp) == vis.end()) {
q.push(temp);
vis.insert(temp);
}
}
temp = prev;
}
}
ans++;
}
return -1;
}
};