Algorithm for Checking Solvability of 15-Tile Puzzle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool isSolvable(string &str)
{
int pos = str.find('*'); //find the index of * in the string

//step 1: move black to lower right corner
for (; pos%4 < 3; pos++) str[pos] = str[pos+1]; //move blank right
for (; pos < 15; pos+=4) str[pos] = str[pos+4]; //move blank down

//step 2: count inversions
int inv = 0;
for (int i=0; i < 14; i++)
for (int j=i+1; j str[j]) inv++;

//step 3: check pivot
if (inv%2==0) return true; //if even, solvable
else return false; //otherwise, unsolvable
}