-
Notifications
You must be signed in to change notification settings - Fork 1
/
puzzle_problem.cpp
66 lines (59 loc) · 1.35 KB
/
puzzle_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
#include <iostream>
#define N 4
using namespace std;
int getInvCount(int arr[])
{
int inv_count = 0;
for (int i = 0; i < N * N - 1; i++)
{
for (int j = i + 1; j < N * N; j++)
{
if (arr[j] && arr[i] && arr[i] > arr[j])
inv_count++;
}
}
return inv_count;
}
int findXPosition(int puzzle[N][N])
{
for (int i = N - 1; i >= 0; i--)
for (int j = N - 1; j >= 0; j--)
if (puzzle[i][j] == 0)
return N - i;
return -1;
}
bool isSolvable(int puzzle[N][N])
{
int invCount = getInvCount((int *)puzzle);
if (N & 1)
return !(invCount & 1);
else
{
int pos = findXPosition(puzzle);
if (pos & 1)
return !(invCount & 1);
else
return invCount & 1;
}
}
int main()
{
int puzzle[N][N] =
{
{12, 1, 10, 2},
{7, 11, 4, 14},
{5, 0, 9, 15},
{8, 13, 6, 3},
};
cout << "Puzzle :\n"
<< "----------" << endl;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout << puzzle[i][j] << " ";
cout << endl;
}
cout << "----------" << endl;
isSolvable(puzzle) ? cout << "Solvable" : cout << "Not Solvable";
return 0;
}