Algorithm for Checking Solvability of 15-Tile Puzzle


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
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s