-
Notifications
You must be signed in to change notification settings - Fork 2
/
problem.cpp
123 lines (101 loc) · 2.55 KB
/
problem.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include<iostream>
#include"puzzle.h"
#include"problem.h"
using namespace std;
int goalTest(Puzzle * curr_node)
{
int goal_state[9] = {8,0,1,2,3,4,5,6,7};
for(int i=0; i<9; ++i)
{
if(curr_node->state[i] != goal_state[i])
return 0;
}
return 1;
}
int heuristic(Puzzle * curr_node)
{
//heuristic is the number of the misplaced tiles in the state.
int goal_state[9] = {8,0,1,2,3,4,5,6,7};
int heuristic = 0;
for(int i=0; i<9; ++i)
{
if(curr_node->state[i] != goal_state[i])
{
heuristic++;
}
}
return heuristic;
}
Puzzle* transition(Puzzle *curr_node, int action)
{
Puzzle *next_node = new Puzzle;
int blank_pos = curr_node->state[0];
int tile;
if(action==1)//up action
{
tile = blank_pos - 3;
for(int i=1;i<9;++i)
{
if(curr_node->state[i]==tile)
{
next_node->state[0] = tile;
next_node->state[i] = blank_pos;
}
else
{
next_node->state[i] = curr_node->state[i];
}
}
}
else if(action==2)//left action
{
tile = blank_pos-1;
for(int i=0;i<9;++i)
{
if(curr_node->state[i]==blank_pos-1)
{
next_node->state[0] = tile;
next_node->state[i] = blank_pos;
}
else
{
next_node->state[i] = curr_node->state[i];
}
}
}
else if(action==4)//down action
{
tile = blank_pos+3;
for(int i=0;i<9;++i)
{
if(curr_node->state[i]==blank_pos+3)
{
next_node->state[0] = tile;
next_node->state[i] = blank_pos;
}
else
{
next_node->state[i] = curr_node->state[i];
}
}
}
else//right action
{
tile = blank_pos+1;
for(int i=0;i<9;++i)
{
if(curr_node->state[i]==blank_pos+1)
{
next_node->state[0] = tile;
next_node->state[i] = blank_pos;
}
else
{
next_node->state[i] = curr_node->state[i];
}
}
}
next_node->parent = curr_node;
next_node->path_cost = curr_node->path_cost + 1;
return next_node;
}