Algorithm for Checking Solvability of 15-Tile Puzzle
2012-04-13

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
}