forked from mayaanayak/OpenFlightsGraphAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiddfs.cpp
More file actions
54 lines (49 loc) · 2.01 KB
/
iddfs.cpp
File metadata and controls
54 lines (49 loc) · 2.01 KB
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
43
44
45
46
47
48
49
50
51
52
53
// Referenced Wikipedia pseudocode
#include "iddfs.h"
IDDFS::IDDFS(makeGraph mkg): mkg_(mkg) {}
bool IDDFS::runIDDFS(int start, int dest, int max_flights) {
// Find the indices corresponding to the inputted source and destination IDs
int startIdx = mkg_.getAirportIndex(start);
int destIdx = mkg_.getAirportIndex(dest);
// Iterate from 0 to the maximum number of flights, and return if we find the destination airport
for (int i = 0; i <= max_flights; i++) {
std::pair<int, bool> foundremaining = DLS(startIdx, destIdx, i);
int found = foundremaining.first;
bool remaining = foundremaining.second;
if (found != std::numeric_limits<int>::max()) {
return true;
}
if (!remaining) {
return false;
}
}
return false;
}
std::pair<int, bool> IDDFS::DLS(int startIdx, int destIdx, int limit) {
if (limit == 0) {
// Return when the destination airport is found
if (startIdx == destIdx) {
return (std::pair<int,bool>(startIdx,true));
// Return that the destination airport was not found
} else {
return (std::pair<int, bool>(std::numeric_limits<int>::max(), true));
}
}
bool any_remaining = false;
std::vector<int> neighbor_indices = mkg_.getNeighbors(startIdx);
for (size_t i = 0; i < neighbor_indices.size(); i++) {
int child = neighbor_indices[i];
std::pair<int, bool> foundremaining = DLS(child, destIdx, limit - 1);
int found = foundremaining.first;
bool remaining = foundremaining.second;
// Return that the destination airport was found
if (found != std::numeric_limits<int>::max()) {
return (std::pair<int, bool>(found, true));
}
if (remaining) {
any_remaining = true;
}
}
// Return that the destination airport was not found, and whether there are remaining airports to explore
return (std::pair<int, bool>(std::numeric_limits<int>::max(), any_remaining));
}