The Wayback Machine - https://web.archive.org/web/20240704223802/https://www.geeksforgeeks.org/check-instance-8-puzzle-solvable/
Open In App

How to check if an instance of 8 puzzle is solvable?

Last Updated : 26 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

What is 8 puzzle? 

Given a 3×3 board with 8 tiles (every tile has one number from 1 to 8) and one empty space. The objective is to place the numbers on tiles in order using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space

8puzzle1

How to find if given state is solvable? 

Following are two examples, the first example can reach goal state by a series of slides. The second example cannot. 

8puzzle

Following is simple rule to check if a 8 puzzle is solvable. 

It is not possible to solve an instance of 8 puzzle if number of inversions is odd in the input state. 

In the examples given in above figure, the first example has 10 inversions, therefore solvable. The second example has 11 inversions, therefore unsolvable.

What is inversion? 

A pair of tiles form an inversion if the values on tiles are in reverse order of their appearance in goal state. For example, the following instance of 8 puzzle has two inversions, (8, 6) and (8, 7). 

   1   2   3
   4   _   5
   8   6   7      

Following are the implementations to check whether a given instance of 8 puzzle is solvable or not. The idea is simple, we count inversions in the given 8 puzzle. 

C++




// C++ program to check if a given instance of 8 puzzle is solvable or not
#include <iostream>
using namespace std;
 
// A utility function to count inversions in given array 'arr[]'
int getInvCount(int arr[])
{
    int inv_count = 0;
    for (int i = 0; i < 9 - 1; i++)
        for (int j = i+1; j < 9; j++)
             // Value 0 is used for empty space
             if (arr[j] && arr[i] &&  arr[i] > arr[j])
                  inv_count++;
    return inv_count;
}
 
// This function returns true if given 8 puzzle is solvable.
bool isSolvable(int puzzle[3][3])
{
    // Count inversions in given 8 puzzle
    int invCount = getInvCount((int *)puzzle);
 
    // return true if inversion count is even.
    return (invCount%2 == 0);
}
 
/* Driver program to test above functions */
int main()
{
  int puzzle[3][3] =  {{1, 8, 2},
                      {0, 4, 3},  // Value 0 is used for empty space
                      {7, 6, 5}};
  isSolvable(puzzle)? cout << "Solvable":
                      cout << "Not Solvable";
  return 0;
}


Java




// Java program to check if a given
// instance of 8 puzzle is solvable or not
class GFG
{
     
// A utility function to count
// inversions in given array 'arr[]'
static int getInvCount(int[] arr)
{
    int inv_count = 0;
    for (int i = 0; i < 9; i++)
        for (int j = i + 1; j < 9; j++)
         
            // Value 0 is used for empty space
            if (arr[i] > 0 &&
                            arr[j] > 0 && arr[i] > arr[j])
                inv_count++;
    return inv_count;
}
 
// This function returns true
// if given 8 puzzle is solvable.
static boolean isSolvable(int[][] puzzle)
{
    int linearPuzzle[];
    linearPuzzle = new int[9];
    int k = 0;
     
  // Converting 2-D puzzle to linear form
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            linearPuzzle[k++] = puzzle[i][j];
     
    // Count inversions in given 8 puzzle
    int invCount = getInvCount(linearPuzzle);
 
    // return true if inversion count is even.
    return (invCount % 2 == 0);
}
 
/* Driver code */
public static void main (String[] args)
{
    int[][] puzzle = {{1, 8, 2},{0, 4, 3},{7, 6, 5}};
    // in linear
    if(isSolvable(puzzle))
        System.out.println("Solvable");
    else
    System.out.println("Not Solvable");
}
}


Python3




# Python3 program to check if a given
# instance of 8 puzzle is solvable or not
 
# A utility function to count
# inversions in given array 'arr[]'
def getInvCount(arr):
    inv_count = 0
    empty_value = -1
    for i in range(0, 9):
        for j in range(i + 1, 9):
            if arr[j] != empty_value and arr[i] != empty_value and arr[i] > arr[j]:
                inv_count += 1
    return inv_count
 
     
# This function returns true
# if given 8 puzzle is solvable.
def isSolvable(puzzle) :
 
    # Count inversions in given 8 puzzle
    inv_count = getInvCount([j for sub in puzzle for j in sub])
 
    # return true if inversion count is even.
    return (inv_count % 2 == 0)
     
    # Driver code
puzzle = [[8, 1, 2],[-1, 4, 3],[7, 6, 5]]
if(isSolvable(puzzle)) :
    print("Solvable")
else :
    print("Not Solvable")
     
    # This code is contributed by vitorhugooli
    # Fala meu povo desse Brasil varonil 😉


C#




// C# program to check if a given
// instance of 8 puzzle is solvable or not
using System;
 
class GFG
{
     
// A utility function to count
// inversions in given array 'arr[]'
static int getInvCount(int[] arr)
{
    int inv_count = 0;
    for (int i = 0; i < 9; i++)
        for (int j = i + 1; j < 9; j++)
         
            // Value 0 is used for empty space
            if (arr[i] > 0 && arr[j] > 0 && arr[i] > arr[j])
                inv_count++;
    return inv_count;
}
 
// This function returns true
// if given 8 puzzle is solvable.
static bool isSolvable(int[,] puzzle)
{
    int[] linearForm;
    linearForm = new int[9];
    int k = 0;
     
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            linearForm[k++] = puzzle[i, j];
     
    // Count inversions in given 8 puzzle
    int invCount = getInvCount(linearForm);
 
    // return true if inversion count is even.
    return (invCount % 2 == 0);
}
 
/* Driver code */
static void Main()
{
    int[,] puzzle = new int[3,3]{{1, 8, 2},
                            {0, 4, 3}, // Value 0 is used for empty space
                            {7, 6, 5}};
    if(isSolvable(puzzle))
        Console.WriteLine("Solvable");
    else
       Console.WriteLine("Not Solvable");
}
}
 
// This code is contributed by chandan_jnu


PHP




<?php
// PHP program to check if
// a given instance of 8
// puzzle is solvable or not
 
// A utility function to
// count inversions in
// given array 'arr[]'
function getInvCount($arr)
{
    $inv_count = 0;
    for ($i = 0; $i < 9 - 1; $i++)
        for ( $j = $i + 1; $j < 9; $j++)
                $inv_count++;
    return $inv_count;
}
 
// This function returns true
// if given 8 puzzle is solvable.
function isSolvable($puzzle)
{
    // Count inversions in
    // given 8 puzzle
    $invCount = getInvCount($puzzle);
 
    // return true if
    // inversion count is even.
    return ($invCount % 2 == 0);
}
 
// Driver Code
$puzzle = array(array(1, 8, 2),
                array(0, 4, 3), // Value 0 is used
                array(7, 6, 5));// for empty space
                 
if(isSolvable($puzzle) == true)
            echo "Solvable";
        else
            echo "Not Solvable";
                 
// This code is contributed by ajit
?>


Javascript




<script>
 
// JavaScript program to check if a given
// instance of 8 puzzle is solvable or not
 
// A utility function to count inversions
// in given array 'arr[]'
function getInvCount(arr)
{
    let inv_count = 0 ;
    for(let i=0;i<2;i++){
        for(let j=i+1;j<3;j++){
         
            // Value 0 is used for empty space
            if (arr[j][i] > 0 && arr[j][i] > arr[i][j])
                inv_count += 1;
        }
     }
    return inv_count;
}
// This function returns true
// if given 8 puzzle is solvable.
function isSolvable(puzzle)
{
    // Count inversions in given 8 puzzle
    let invCount = getInvCount(puzzle);
    // return true if inversion count is even.
    return (invCount % 2 == 0);
}
 
// Driver code
 
// Value 0 is used for empty space
puzzle = [[1, 8, 2],[0, 4, 3],[7, 6, 5]] ;
if(isSolvable(puzzle))
    document.write("Solvable");
else
    document.write("Not Solvable");
     
</script>


Output

Solvable

Time Complexity: O(1)
Auxiliary Space: O(1)

Note that the above implementation uses simple algorithm for inversion count. It is done this way for simplicity. The code can be optimized to O(nLogn) using the merge sort based algorithm for inversion count.

How does this work? 

The idea is based on the fact the parity of inversions remains same after a set of moves, i.e., if the inversion count is odd in initial stage, then it remain odd after any sequence of moves and if the inversion count is even, then it remains even after any sequence of moves. In the goal state, there are 0 inversions. So we can reach goal state only from a state which has even inversion count.
How parity of inversion count is invariant? 
When we slide a tile, we either make a row move (moving a left or right tile into the blank space), or make a column move (moving a up or down tile to the blank space). 

a) A row move doesn’t change the inversion count. See following example  

   1   2   3    Row Move     1   2   3
   4   _   5   ---------->   _   4   5 
   8   6   7                 8   6   7
  Inversion count remains 2 after the move

   1   2   3    Row Move     1   2   3
   4   _   5   ---------->   4   5   _
   8   6   7                 8   6   7
  Inversion count remains 2 after the move

b) A column move does one of the following three. 
…..(i) Increases inversion count by 2. See following example. 

         1   2   3   Column Move     1   _   3
         4   _   5   ----------->    4   2   5  
         8   6   7                   8   6   7
      Inversion count increases by 2 (changes from 2 to 4)
       

…..(ii) Decreases inversion count by 2

         1   3   4    Column Move     1   3   4
         5   _   6   ------------>    5   2   6
         7   2   8                    7   _   8
      Inversion count decreases by 2 (changes from 5  to 3)

…..(iii) Keeps the inversion count same. 

         1   2   3    Column Move     1   2   3
         4   _   5   ------------>    4   6   5
         7   6   8                    7   _   8
        Inversion count remains 1 after the move 

So if a move either increases/decreases inversion count by 2, or keeps the inversion count same, then it is not possible to change parity of a state by any sequence of row/column moves.

Exercise: How to check if a given instance of 15 puzzle is solvable or not. In a 15 puzzle, we have 4×4 board where 15 tiles have a number and one empty space. Note that the above simple rules of inversion count don’t directly work for 15 puzzle, the rules need to be modified for 15 puzzle.

Related Article: How to check if an instance of 15 puzzle is solvable?

 



Similar Reads

How to check if an instance of 15 puzzle is solvable?
Given a 4×4 board with 15 tiles (every tile has one number from 1 to 15) and one empty space. The objective is to place the numbers on tiles in order using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space. For example, Here X marks the spot to where the elements can be shifted and the final confi
15 min read
Check whether jigsaw puzzle solvable or not
Given a special Jigsaw puzzle consisting of N rows and M columns all identical pieces. Every piece has three tabs and one blank. The task is to check if the puzzle is solvable by placing the pieces in such a way that the tab of one piece fits perfectly into a blank of other piece. Note: Rotate and Translate the pieces to solve the puzzle. Examples:
4 min read
Decision Trees - Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)
Let us solve the classic "fake coin" puzzle using decision trees. There are the two different variants of the puzzle given below. I am providing description of both the puzzles below, try to solve on your own, assume N = 8. Easy: Given a two pan fair balance and N identically looking coins, out of which only one coin is lighter (or heavier). To fig
12 min read
Wrap every continuous instance of given word with some given string
Given two string S1 and S2. The task is to wrap every instance of string S2 in string S1 with some string on either side.Note: Here we will use underscore(_) for the wrapping part. It can be anything as per need, for example some HTML tag, white space, etc.Examples: Input: S1 = "examwill be a examexam", S2 = "exam" Output: "_exam_will be a _examexa
13 min read
Difference between Instance Variable and Class Variable
Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to
2 min read
Instance Simplification Method in Transform and Conquer Technique
Instance simplification is one of the Transform and Conquer techniques. To understand Instance Simplification, first let us understand what is transform and conquer. Transform and Conquer is a technique whose main idea is to transfer the problem into some easier or similar versions using some procedure and then solve that easier or simpler versions
9 min read
Puzzle | Maximum number of Kings on Chessboard without under check
Prerequisite - The Pigeonhole PrincipleProblem statement - Given a 8×8 chessboard, figure out the maximum number of kings that can be placed on the chessboard so that no two kings attack each other, i.e., none of the kings is under check. A king can move only one step at a time any direction on the chessboard (horizontally, vertically and diagonall
3 min read
Puzzle | Message Spreading
There are n students in a class, each in possession of a different funny story. As the students were getting bored in the class, they decided to come up with a game so that they can pass their time. They want to share the funny stories with each other by sending electronic messages. Assume that a sender includes all the funny stories he or she know
3 min read
Puzzle | Minimum distance for Lizard
A lizard is present on one corner of cube, It wants to reach diagonally opposite corner of cube. You have to calculate minimum distance lizard has to cover to reach its destination.Note : Lizard can't fly, it moves along the wall.You are given a representing side of cube.you have to calculate minimum distance lizard has to travel. Examples: Input :
3 min read
Egg Dropping Puzzle with 2 Eggs and K Floors
Given 2 eggs and k floors, find the minimum number of trials needed in worst case. This problem is a specific case of n eggs and k floors.Examples: Input : k = 10 Output : 4 We first try from 4-th floor. Two cases arise, (1) If egg breaks, we have one egg left so we need three more trials. (2) If egg does not break, we try next from 7-th floor. Aga
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg