-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEightPuzzleDFS.cpp
More file actions
79 lines (68 loc) · 1.71 KB
/
Copy pathEightPuzzleDFS.cpp
File metadata and controls
79 lines (68 loc) · 1.71 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
string goalDFS = "123456780";
set<string> visitedDFS;
vector<string> pathDFS;
vector<pair<int, int>> directionsDFS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool isValidDFS(int x, int y) {
return x >= 0 && y >= 0 && x < 3 && y < 3;
}
bool dfs(const string& state) {
if (state == goalDFS) {
pathDFS.push_back(state);
return true;
}
if (visitedDFS.count(state)) return false;
visitedDFS.insert(state);
pathDFS.push_back(state);
int zeroIndex = static_cast<int>(state.find('0'));
int x = zeroIndex / 3;
int y = zeroIndex % 3;
for (auto [dx, dy] : directionsDFS) {
int nx = x + dx;
int ny = y + dy;
if (isValidDFS(nx, ny)) {
int newIndex = nx * 3 + ny;
string newState = state;
swap(newState[zeroIndex], newState[newIndex]);
if (dfs(newState)) return true;
}
}
pathDFS.pop_back();
return false;
}
void printBoardDFS(const string& state) {
for (int i = 0; i < 9; ++i) {
cout << state[i] << ' ';
if (i % 3 == 2) cout << '\n';
}
}
void printPathDFS() {
cout << "Solution Path:\n";
for (const auto& s : pathDFS) {
printBoardDFS(s);
cout << '\n';
}
}
int main() {
cout << "Enter initial state (use 0 for blank):\n";
string start;
cin >> start;
if (dfs(start)) printPathDFS();
else cout << "No solution found.\n";
return 0;
}