8 puzzle Problem - GeeksforGeeks (2024)

Last Updated : 26 Jul, 2024

Comments

Improve

Recommended Problem

Minimum Cost to cut a board into squares

Show Topics

Topics:

GreedyAlgorithms

Solve Problem

Medium

60.83%

17.2K

Given a 3×3 board with 8 tiles (each numbered from 1 to 8) and one empty space, the objective is to place the numbers to match the final configuration using the empty space. We can slide four adjacent tiles (left, right, above, and below) into the empty space.

8 puzzle Problem - GeeksforGeeks (2)


1. 8 puzzle Problem using DFS (Brute-Force)

We can perform a depth-first search on state-space (Set of all configurations of a given problem i.e. all states that can be reached from the initial state) tree.

  • Depth-first search on state-space tree.
  • Successive moves may take us away from the goal.
  • Inefficient as it explores all paths equally.

Idea: DFS explores as far as possible along each branch before backtracking. It is an exhaustive search technique used to traverse or search tree or graph data structures. It starts at the root node and explores as far as possible along each branch before backtracking.

Approach:

  1. Start from the root node.
  2. Explore the leftmost child node recursively until you reach a leaf node or a goal state.
  3. If a goal state is reached, return the solution.
  4. If a leaf node is reached without finding a solution, backtrack to explore other branches.

8 puzzle Problem - GeeksforGeeks (3)

2. 8 puzzle Problem using BFS (Brute-Force)

We can perform a Breadth-first search on the state space tree. This always finds a goal state nearest to the root. But no matter what the initial state is, the algorithm attempts the same sequence of moves like DFS.

  • Breadth-first search on the state-space tree.
  • Always finds the nearest goal state.
  • Same sequence of moves irrespective of initial state.

Idea: BFS explores all neighbor nodes at the present depth before moving on to nodes at the next depth level. It is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root and explores the neighbor nodes first, before moving to the next level neighbors.

Approach:

  1. Start from the root node.
  2. Explore all neighboring nodes at the present depth.
  3. Move to the next depth level and repeat the process.
  4. If a goal state is reached, return the solution.

3. 8 puzzle Problem using Branch and Bound

DFS and BFS Approach Limitations

  • DFS: Can get stuck exploring deep paths that do not lead to the goal, potentially leading to excessive memory usage and slow performance.
  • BFS: Explores all nodes at the present depth before moving to the next depth level, which can be inefficient as it does not prioritize more promising paths.

Optimizations with Branch and Bound

Branch and Bound (B&B) enhances both DFS and BFS by integrating a cost function to guide the search:

  1. Intelligent Node Selection:
    • Instead of exploring nodes blindly (DFS) or equally (BFS), B&B uses a cost function to prioritize nodes that are closer to the goal, reducing unnecessary computations.
  2. Pruning:
    • B&B prunes paths that are unlikely to lead to an optimal solution, saving time and memory.

The search for an answer node can often be speeded by using an “intelligent” ranking function, also called an approximate cost function to avoid searching in sub-trees that do not contain an answer node. It is similar to the backtracking technique but uses a BFS-like search.

Approach:

  1. Use a priority queue to store live nodes.
  2. Initialize the cost function for the root node.
  3. Expand the node with the least cost.
  4. If a goal state is reached, return the solution.
  5. Continue expanding nodes until a goal state is found or the priority queue is empty.

Types of Nodes in Branch and Bound Approach

  1. Live Node: A node that has been generated but whose children have not yet been explored. It is waiting to be processed.
  2. E-node (Expanding Node): The live node currently being expanded or explored. Its children are being generated.
  3. Dead Node: A node that is not to be expanded or explored further, either because it is a solution or because its cost is too high.

Cost Function

The cost function balances the actual cost to reach the node and the heuristic estimate to reach the goal. It combines two components:

  • g(X): The cost to reach the current node from the root node.
  • h(X): The estimated cost to reach the goal node from the current node.

Cost Function Formula: C(X)=g(X)+h(X)

Deriving the Cost Function for the 8-Puzzle Problem

For the 8-puzzle problem, the cost function can be defined as:

  • g(X): The number of moves taken to reach the current state from the initial state.
  • h(X): The number of misplaced tiles (tiles that are not in their goal position).
Thus, the cost function C(X) for a node X can be expressed as: C(X)=g(X)+h(X) 

where:

  • g(X) is the number of moves taken so far.
  • h(X) is the number of tiles not in their goal positions.

The below diagram shows the path followed by the above algorithm to reach the final configuration from the given initial configuration of the 8-Puzzle. Note that only nodes having the least value of cost function are expanded.

8 puzzle Problem - GeeksforGeeks (4)

C++14
// Program to print path from root node to destination node// for N*N -1 puzzle algorithm using Branch and Bound// The solution assumes that instance of puzzle is solvable#include <bits/stdc++.h>using namespace std;#define N 3// state space tree nodesstruct Node{ // stores the parent node of the current node // helps in tracing path when the answer is found Node* parent; // stores matrix int mat[N][N]; // stores blank tile coordinates int x, y; // stores the number of misplaced tiles int cost; // stores the number of moves so far int level;};// Function to print N x N matrixint printMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%d ", mat[i][j]); printf("\n"); }}// Function to allocate a new nodeNode* newNode(int mat[N][N], int x, int y, int newX, int newY, int level, Node* parent){ Node* node = new Node; // set pointer for path to root node->parent = parent; // copy data from parent node to current node memcpy(node->mat, mat, sizeof node->mat); // move tile by 1 position swap(node->mat[x][y], node->mat[newX][newY]); // set number of misplaced tiles node->cost = INT_MAX; // set number of moves so far node->level = level; // update new blank tile coordinates node->x = newX; node->y = newY; return node;}// bottom, left, top, rightint row[] = { 1, 0, -1, 0 };int col[] = { 0, -1, 0, 1 };// Function to calculate the number of misplaced tiles// ie. number of non-blank tiles not in their goal positionint calculateCost(int initial[N][N], int final[N][N]){ int count = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (initial[i][j] && initial[i][j] != final[i][j]) count++; return count;}// Function to check if (x, y) is a valid matrix coordinateint isSafe(int x, int y){ return (x >= 0 && x < N && y >= 0 && y < N);}// print path from root node to destination nodevoid printPath(Node* root){ if (root == NULL) return; printPath(root->parent); printMatrix(root->mat); printf("\n");}// Comparison object to be used to order the heapstruct comp{ bool operator()(const Node* lhs, const Node* rhs) const { return (lhs->cost + lhs->level) > (rhs->cost + rhs->level); }};// Function to solve N*N - 1 puzzle algorithm using// Branch and Bound. x and y are blank tile coordinates// in initial statevoid solve(int initial[N][N], int x, int y, int final[N][N]){ // Create a priority queue to store live nodes of // search tree; priority_queue<Node*, std::vector<Node*>, comp> pq; // create a root node and calculate its cost Node* root = newNode(initial, x, y, x, y, 0, NULL); root->cost = calculateCost(initial, final); // Add root to list of live nodes; pq.push(root); // Finds a live node with least cost, // add its childrens to list of live nodes and // finally deletes it from the list. while (!pq.empty()) { // Find a live node with least estimated cost Node* min = pq.top(); // The found node is deleted from the list of // live nodes pq.pop(); // if min is an answer node if (min->cost == 0) { // print the path from root to destination; printPath(min); return; } // do for each child of min // max 4 children for a node for (int i = 0; i < 4; i++) { if (isSafe(min->x + row[i], min->y + col[i])) { // create a child node and calculate // its cost Node* child = newNode(min->mat, min->x, min->y, min->x + row[i], min->y + col[i], min->level + 1, min); child->cost = calculateCost(child->mat, final); // Add child to list of live nodes pq.push(child); } } }}// Driver codeint main(){ // Initial configuration // Value 0 is used for empty space int initial[N][N] = { {1, 2, 3}, {5, 6, 0}, {7, 8, 4} }; // Solvable Final configuration // Value 0 is used for empty space int final[N][N] = { {1, 2, 3}, {5, 8, 6}, {0, 7, 4} }; // Blank tile coordinates in initial // configuration int x = 1, y = 2; solve(initial, x, y, final); return 0;}
Java
// Java Program to print path from root node to destination node// for N*N -1 puzzle algorithm using Branch and Bound// The solution assumes that instance of puzzle is solvableimport java.io.*;import java.util.*;class GFG{  public static int N = 3; public static class Node {  // stores the parent node of the current node // helps in tracing path when the answer is found Node parent; int mat[][] = new int[N][N];// stores matrix int x, y;// stores blank tile coordinates int cost;// stores the number of misplaced tiles int level;// stores the number of moves so far }  // Function to print N x N matrix public static void printMatrix(int mat[][]){ for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ System.out.print(mat[i][j]+" "); } System.out.println(""); } }  // Function to allocate a new node public static Node newNode(int mat[][], int x, int y,  int newX, int newY, int level,  Node parent){ Node node = new Node(); node.parent = parent;// set pointer for path to root  // copy data from parent node to current node node.mat = new int[N][N]; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ node.mat[i][j] = mat[i][j]; } }  // move tile by 1 position int temp = node.mat[x][y]; node.mat[x][y] = node.mat[newX][newY]; node.mat[newX][newY]=temp;  node.cost = Integer.MAX_VALUE;// set number of misplaced tiles node.level = level;// set number of moves so far  // update new blank tile coordinates node.x = newX; node.y = newY;  return node; }  // bottom, left, top, right public static int row[] = { 1, 0, -1, 0 }; public static int col[] = { 0, -1, 0, 1 };  // Function to calculate the number of misplaced tiles // ie. number of non-blank tiles not in their goal position public static int calculateCost(int initialMat[][], int finalMat[][]) { int count = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (initialMat[i][j]!=0 && initialMat[i][j] != finalMat[i][j]) count++; return count; }  // Function to check if (x, y) is a valid matrix coordinate public static int isSafe(int x, int y) { return (x >= 0 && x < N && y >= 0 && y < N)?1:0; }  // print path from root node to destination node public static void printPath(Node root){ if(root == null){ return; } printPath(root.parent); printMatrix(root.mat); System.out.println(""); }  // Comparison object to be used to order the heap public static class comp implements Comparator<Node>{ @Override public int compare(Node lhs, Node rhs){ return (lhs.cost + lhs.level) > (rhs.cost+rhs.level)?1:-1; } }   // Function to solve N*N - 1 puzzle algorithm using // Branch and Bound. x and y are blank tile coordinates // in initial state public static void solve(int initialMat[][], int x,  int y, int finalMat[][]) {  // Create a priority queue to store live nodes of search tree PriorityQueue<Node> pq = new PriorityQueue<>(new comp());  // create a root node and calculate its cost Node root = newNode(initialMat, x, y, x, y, 0, null); root.cost = calculateCost(initialMat,finalMat);  // Add root to list of live nodes; pq.add(root);  // Finds a live node with least cost, // add its childrens to list of live nodes and // finally deletes it from the list. while(!pq.isEmpty()) { Node min = pq.peek();// Find a live node with least estimated cost pq.poll();// The found node is deleted from the list of live nodes  // if min is an answer node if(min.cost == 0){ printPath(min);// print the path from root to destination; return; } // do for each child of min // max 4 children for a node for (int i = 0; i < 4; i++) { if (isSafe(min.x + row[i], min.y + col[i])>0) { // create a child node and calculate // its cost Node child = newNode(min.mat, min.x, min.y, min.x + row[i],min.y + col[i], min.level + 1, min); child.cost = calculateCost(child.mat, finalMat);  // Add child to list of live nodes pq.add(child); } } } }  //Driver Code public static void main (String[] args) {  // Initial configuration // Value 0 is used for empty space int initialMat[][] = { {1, 2, 3}, {5, 6, 0}, {7, 8, 4} };  // Solvable Final configuration // Value 0 is used for empty space int finalMat[][] = { {1, 2, 3}, {5, 8, 6}, {0, 7, 4} };  // Blank tile coordinates in initial // configuration int x = 1, y = 2;  solve(initialMat, x, y, finalMat); }}// This code is contributed by shruti456rawal
Python
# Python3 program to print the path from root # node to destination node for N*N-1 puzzle # algorithm using Branch and Bound# The solution assumes that instance of # puzzle is solvable# Importing copy for deepcopy functionimport copy# Importing the heap functions from python # library for Priority Queuefrom heapq import heappush, heappop# This variable can be changed to change# the program from 8 puzzle(n=3) to 15 # puzzle(n=4) to 24 puzzle(n=5)...n = 3# bottom, left, top, rightrow = [ 1, 0, -1, 0 ]col = [ 0, -1, 0, 1 ]# A class for Priority Queueclass priorityQueue: # Constructor to initialize a # Priority Queue def __init__(self): self.heap = [] # Inserts a new key 'k' def push(self, k): heappush(self.heap, k) # Method to remove minimum element  # from Priority Queue def pop(self): return heappop(self.heap) # Method to know if the Queue is empty def empty(self): if not self.heap: return True else: return False# Node structureclass node: def __init__(self, parent, mat, empty_tile_pos, cost, level): # Stores the parent node of the  # current node helps in tracing  # path when the answer is found self.parent = parent # Stores the matrix self.mat = mat # Stores the position at which the # empty space tile exists in the matrix self.empty_tile_pos = empty_tile_pos # Stores the number of misplaced tiles self.cost = cost # Stores the number of moves so far self.level = level # This method is defined so that the  # priority queue is formed based on  # the cost variable of the objects def __lt__(self, nxt): return self.cost < nxt.cost# Function to calculate the number of # misplaced tiles ie. number of non-blank# tiles not in their goal positiondef calculateCost(mat, final) -> int: count = 0 for i in range(n): for j in range(n): if ((mat[i][j]) and (mat[i][j] != final[i][j])): count += 1 return countdef newNode(mat, empty_tile_pos, new_empty_tile_pos, level, parent, final) -> node: # Copy data from parent matrix to current matrix new_mat = copy.deepcopy(mat) # Move tile by 1 position x1 = empty_tile_pos[0] y1 = empty_tile_pos[1] x2 = new_empty_tile_pos[0] y2 = new_empty_tile_pos[1] new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1] # Set number of misplaced tiles cost = calculateCost(new_mat, final) new_node = node(parent, new_mat, new_empty_tile_pos, cost, level) return new_node# Function to print the N x N matrixdef printMatrix(mat): for i in range(n): for j in range(n): print("%d " % (mat[i][j]), end = " ") print()# Function to check if (x, y) is a valid# matrix coordinatedef isSafe(x, y): return x >= 0 and x < n and y >= 0 and y < n# Print path from root node to destination nodedef printPath(root): if root == None: return printPath(root.parent) printMatrix(root.mat) print()# Function to solve N*N - 1 puzzle algorithm# using Branch and Bound. empty_tile_pos is# the blank tile position in the initial state.def solve(initial, empty_tile_pos, final): # Create a priority queue to store live # nodes of search tree pq = priorityQueue() # Create the root node cost = calculateCost(initial, final) root = node(None, initial, empty_tile_pos, cost, 0) # Add root to list of live nodes pq.push(root) # Finds a live node with least cost, # add its children to list of live  # nodes and finally deletes it from  # the list. while not pq.empty(): # Find a live node with least estimated # cost and delete it from the list of  # live nodes minimum = pq.pop() # If minimum is the answer node if minimum.cost == 0: # Print the path from root to # destination; printPath(minimum) return # Generate all possible children for i in range(4): new_tile_pos = [ minimum.empty_tile_pos[0] + row[i], minimum.empty_tile_pos[1] + col[i], ] if isSafe(new_tile_pos[0], new_tile_pos[1]): # Create a child node child = newNode(minimum.mat, minimum.empty_tile_pos, new_tile_pos, minimum.level + 1, minimum, final,) # Add child to list of live nodes pq.push(child)# Driver Code# Initial configuration# Value 0 is used for empty spaceinitial = [ [ 1, 2, 3 ], [ 5, 6, 0 ], [ 7, 8, 4 ] ]# Solvable Final configuration# Value 0 is used for empty spacefinal = [ [ 1, 2, 3 ], [ 5, 8, 6 ], [ 0, 7, 4 ] ]# Blank tile coordinates in # initial configurationempty_tile_pos = [ 1, 2 ]# Function call to solve the puzzlesolve(initial, empty_tile_pos, final)# This code is contributed by Kevin Joshi
C#
using System;using System.Collections.Generic;class GFG{ public static int N = 3; public class Node { // Stores the parent node of the current node // Helps in tracing the path when the answer is found public Node parent; public int[,] mat = new int[N, N]; // Stores the matrix public int x, y; // Stores blank tile coordinates public int cost; // Stores the number of misplaced tiles public int level; // Stores the number of moves so far } // Function to print N x N matrix public static void PrintMatrix(int[,] mat) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { Console.Write(mat[i, j] + " "); } Console.WriteLine(); } } // Function to allocate a new node public static Node NewNode(int[,] mat, int x, int y, int newX, int newY, int level, Node parent) { Node node = new Node(); node.parent = parent; // Set pointer for the path to root // Copy data from the parent node to the current node node.mat = new int[N, N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { node.mat[i, j] = mat[i, j]; } } // Move the tile by 1 position int temp = node.mat[x, y]; node.mat[x, y] = node.mat[newX, newY]; node.mat[newX, newY] = temp; node.cost = int.MaxValue; // Set the number of misplaced tiles node.level = level; // Set the number of moves so far // Update new blank tile coordinates node.x = newX; node.y = newY; return node; } // Bottom, left, top, right public static int[] row = { 1, 0, -1, 0 }; public static int[] col = { 0, -1, 0, 1 }; // Function to calculate the number of misplaced tiles // i.e., the number of non-blank tiles not in their goal position public static int CalculateCost(int[,] initialMat, int[,] finalMat) { int count = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (initialMat[i, j] != 0 && initialMat[i, j] != finalMat[i, j]) { count++; } } } return count; } // Function to check if (x, y) is a valid matrix coordinate public static int IsSafe(int x, int y) { return (x >= 0 && x < N && y >= 0 && y < N) ? 1 : 0; } // Print the path from the root node to the destination node public static void PrintPath(Node root) { if (root == null) { return; } PrintPath(root.parent); PrintMatrix(root.mat); Console.WriteLine(); } // Comparison object to be used to order the heap public class Comp : IComparer<Node> { public int Compare(Node lhs, Node rhs) { return (lhs.cost + lhs.level) > (rhs.cost + rhs.level) ? 1 : -1; } } // Function to solve N*N - 1 puzzle algorithm using // Branch and Bound. x and y are blank tile coordinates // in the initial state public static void Solve(int[,] initialMat, int x, int y, int[,] finalMat) { // Create a priority queue to store live nodes of the search tree var pq = new SortedSet<Node>(new Comp()); // Create a root node and calculate its cost Node root = NewNode(initialMat, x, y, x, y, 0, null); root.cost = CalculateCost(initialMat, finalMat); // Add the root to the list of live nodes pq.Add(root); // Find a live node with the least cost, // add its children to the list of live nodes, and // finally remove it from the list while (pq.Count > 0) { Node min = pq.Min; // Find a live node with the least estimated cost pq.Remove(min); // The found node is removed from the list of live nodes // If min is an answer node if (min.cost == 0) { PrintPath(min); // Print the path from the root to the destination return; } // Do for each child of min // Max 4 children for a node for (int i = 0; i < 4; i++) { if (IsSafe(min.x + row[i], min.y + col[i]) > 0) { // Create a child node and calculate its cost Node child = NewNode(min.mat, min.x, min.y, min.x + row[i], min.y + col[i], min.level + 1, min); child.cost = CalculateCost(child.mat, finalMat); // Add the child to the list of live nodes pq.Add(child); } } } } // Driver Code public static void Main(string[] args) { // Initial configuration // Value 0 is used for empty space int[,] initialMat = { {1, 2, 3}, {5, 6, 0}, {7, 8, 4} }; // Solvable Final configuration // Value 0 is used for empty space int[,] finalMat = { {1, 2, 3}, {5, 8, 6}, {0, 7, 4} }; // Blank tile coordinates in the initial configuration int x = 1, y = 2; Solve(initialMat, x, y, finalMat); }}
JavaScript
// Program to print path from root node to destination node// for N*N - 1 puzzle algorithm using Branch and Bound// The solution assumes that the instance of the puzzle is solvableconst N = 3;// State space tree nodesclass Node { constructor(mat, x, y, level, parent) { // Stores the parent node of the current node // Helps in tracing the path when the answer is found this.parent = parent; // Stores matrix this.mat = mat.map(row => [...row]); // Stores blank tile coordinates this.x = x; this.y = y; // Stores the number of misplaced tiles this.cost = Infinity; // Stores the number of moves so far this.level = level; }}// Function to print N x N matrixfunction printMatrix(mat) { for (let i = 0; i < N; i++) { console.log(mat[i].join(' ')); } console.log('\n');}// Function to allocate a new nodefunction newNode(mat, x, y, newX, newY, level, parent) { const node = new Node(mat, x, y, level, parent); // Move tile by 1 position [node.mat[x][y], node.mat[newX][newY]] = [node.mat[newX][newY], node.mat[x][y]]; // Update new blank tile coordinates node.x = newX; node.y = newY; return node;}// Bottom, left, top, rightconst row = [1, 0, -1, 0];const col = [0, -1, 0, 1];// Function to calculate the number of misplaced tiles// i.e., number of non-blank tiles not in their goal positionfunction calculateCost(initial, final) { let count = 0; for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) if (initial[i][j] && initial[i][j] !== final[i][j]) count++; return count;}// Function to check if (x, y) is a valid matrix coordinatefunction isSafe(x, y) { return x >= 0 && x < N && y >= 0 && y < N;}// Print path from root node to destination nodefunction printPath(root) { if (!root) return; printPath(root.parent); printMatrix(root.mat);}// Comparison object to be used to order the heapclass comp { static compare(lhs, rhs) { return (lhs.cost + lhs.level) > (rhs.cost + rhs.level); }}// Function to solve N*N - 1 puzzle algorithm using// Branch and Bound. x and y are blank tile coordinates// in the initial statefunction solve(initial, x, y, final) { // Create an array to store live nodes of the search tree const pq = []; // Create a root node and calculate its cost const root = newNode(initial, x, y, x, y, 0, null); root.cost = calculateCost(initial, final); // Add root to the array of live nodes pq.push(root); // Find a live node with the least cost, // add its children to the array of live nodes, and // finally delete it from the array while (pq.length > 0) { // Find a live node with the least estimated cost pq.sort(comp.compare); const min = pq.shift(); // If min is an answer node if (min.cost === 0) { // Print the path from root to destination printPath(min); return; } // Do for each child of min // Max 4 children for a node for (let i = 0; i < 4; i++) { if (isSafe(min.x + row[i], min.y + col[i])) { // Create a child node and calculate its cost const child = newNode(min.mat, min.x, min.y, min.x + row[i], min.y + col[i], min.level + 1, min); child.cost = calculateCost(child.mat, final); // Add child to the array of live nodes pq.push(child); } } }}// Driver code// Initial configuration// Value 0 is used for empty spaceconst initial = [ [1, 2, 3], [5, 6, 0], [7, 8, 4]];// Solvable Final configuration// Value 0 is used for empty spaceconst final = [ [1, 2, 3], [5, 8, 6], [0, 7, 4]];// Blank tile coordinates in the initial configurationconst startX = 1, startY = 2;solve(initial, startX, startY, final);// This code is contributed by shivamgupta310570

Output :

1 2 3 
5 6 0
7 8 4
1 2 3
5 0 6
7 8 4
1 2 3
5 8 6
7 0 4
1 2 3
5 8 6
0 7 4

The time complexity of this algorithm is O(N^2 * N!) where N is the number of tiles in the puzzle, and the space complexity is O(N^2).



A

Aditya Goel

8 puzzle Problem - GeeksforGeeks (5)

Improve

Previous Article

Implementation of 0/1 Knapsack using Branch and Bound

Next Article

Job Assignment Problem using Branch And Bound

Please Login to comment...

Similar Reads

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 Crossword Puzzle Of The Week #20 (KnapSack Problem) In this issue of Crossword Puzzle of the Week, we will dive into the topic of the Knapsack Problem. The solution to the crossword puzzle is provided at the end. HINTS:Across: 1. In _____ Knapsack, we can break items for maximizing the total value of the knapsack. 2. 0/1 Knapsack problem has both properties (Overlapping Subproblem and Optimal Substr 2 min read Secretary Problem (A Optimal Stopping Problem) The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on 12 min read Transportation Problem | Set 7 ( Degeneracy in Transportation Problem ) Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution. 3 min read Difference between 0/1 Knapsack problem and Fractional Knapsack problem What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su 13 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 Puzzle | Cut Blue Painted Cube A solid, n-inch cube of wood is coated with blue paint on all six sides. Then the cube is cut into smaller one-inch cubes. These new one-inch cubes will have either Three blue sides, Two blue sides, One blue side, or No blue sides. How many of each type 1 - inch cube will there be? Solution: This puzzle can be solved logically or mathematically. Af 2 min read Puzzle | Selling Chocolates Ram and Shyam were selling chocolates. Ram was selling at the rate of 2 pieces/rupee and Shyam was selling at the rate of 3 pieces/rupee. Now both of them decided that they will mix their chocolates and sell them at the rate of 5 pieces for 2 rupees. Now after selling whole chocolates, they found that the total collection is rupees 7 less than what 1 min read Puzzle | Neighbors in a round table There are 6 persons seating on a round table in which two individual have the same names. What is the probability that the two same-named individuals will be neighbors? Solution(Method 1): Total no of ways in which 6 persons can sit on a round table is (6-1)! = 5! = 120. If we consider two same-named individuals as one person there are 5 persons wh 1 min read A Product Array Puzzle | Set 3 Given an array arr[] consisting of N integers, the task is to construct a Product array of the same size without using division ('/') operator such that each array element becomes equal to the product of all the elements of arr[] except arr[i]. Examples: Input: arr[] = {10, 3, 5, 6, 2}Output: 180 600 360 300 900Explanation:3 * 5 * 6 * 2 is the prod 10 min read Puzzle | Disclosing Secret Problem Statement: A secret can be told only to 2 persons in 5 minutes. The same person tells to 2 more persons and so on. So How long will take to spread a secret to 768 persons? Solution: In the beginning, let only 1 person know the secret. Now, this 1 person will tell disclose the secret to 2 other persons in 5 mins. (Secret known = 2, Remaining 2 min read Puzzle | The Bridge Riddle Puzzle: You are a scientist who works in a lab. You are in the lab and accidentally, you pull the lever with the skull symbol which released the zombies trapped inside the prison of the Lab. The zombies started to come out of prison. You need to get away and safe from them. With you are the janitor, the lab assistant and the old professor who work 2 min read Puzzle | Dividing a Square into N smaller squares Puzzle: Find all values of N for which one can dissect a square into N smaller squares, and outline an algorithm for doing such a dissection. Solution: The basic point to observe is a square has 4 right-angles. So, to divide it into smaller squares each of its right-angle must fall into another square, as more than one right-angle together will res 2 min read Puzzle | Choose the game of Rolling Dice Puzzle: You are risk-averse person. There are Two games are offered to you. Game 1: You roll a dice once and you are paid one trillion times the number of dots on the upturned face of the dice.Game 2: You roll a dice one trillion times. For each roll, you are paid Rs 1 times the number of dots on the upturned face of the dice. Which game do you pre 1 min read Puzzle | Place numbers 1 to 9 in a Circle such that sum of every triplet in straight line is 15 Place the numbers 1 to 9 in a circle, so that wherever there are three in a straight line they shall add up to 15. SOLUTION:[video mp4="https://media.geeksforgeeks.org/wp-content/uploads/20200710130155/wpv.mp4"][/video]The sum of first number and last number is ten ( 1 + 9 = 10 ).Similarly, the sum of second number and second last element is also t 2 min read Puzzle | Connect 9 circles each arranged at center of a Matrix using 3 straight lines Consider 9 circles each arranged at the center of cells of a 2-D matrix of shape 3*3. Draw 3 straight lines without removing pen from paper such that each of the 9 circles is in contact with at least one line. Solution: A similar problem is present here Connect 9 dots using 4 lines. The difference from above problem is that here there are 9 circles 1 min read Puzzle | Find the overweight islander There are 12 men on an island. 11 weigh exactly the same, but one of them is slightly lighter or heavier. There is a seesaw to determine who is the odd one out. Find out the minimum number of times the seesaw will be used. Solution: The minimum number of times seesaw will be needed is 3. Explanation: A Divide and Conquer Approach can be used to sol 3 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 Puzzle | The Apocalypse Puzzle:In the new post-apocalyptic world, the world queen is desperately concerned about the birth rate. Therefore, she decrees that all families should ensure that they have one girl or else they face massive fines. If all families abide by this policy-that is, they have continued to have children until they have one girl, at which point they imme 4 min read Crossword Puzzle Of The Week #33(Chessboard Problems) In this issue of Crossword Puzzle of the Week, we will dive into the topic of Chessboard Problems. The solution to the crossword puzzle is provided at the end. HINTS: Across: 1. ________happens when king is in a position where it is under attack and cannot escape capture on the next move.5. A standard chessboard has 8 ____and 8 column, in which eve 1 min read Solve the Crossword Puzzle A 10 x 10 Crossword grid is provided, along with a set of words (or names of places) which need to be filled into the grid. The cells in the grid are initially, either + signs or - signs. Cells marked with a '+' have to be left as they are. Cells marked with a '-' need to be filled up with an appropriate character. You are also given an array of wo 15+ min read A Boolean Array Puzzle Input: A array arr[] of two elements having value 0 and 1Output: Make both elements 0. Specifications: Following are the specifications to follow. 1) It is guaranteed that one element is 0 but we do not know its position.2) We can't say about another element it can be 0 or 1.3) We can only complement array elements, no other operation like and, or, 4 min read Eggs dropping puzzle | Set 2 Given N eggs and K floors, the task is to find the minimum number of trials needed, in the worst case, to find the floor below which all floors are safe. A floor is safe if dropping an egg from it does not break the egg. Please refer n eggs and k floors for more insight. Examples: Input: N = 2, K = 10 Output: 4 Explanation: The first trial was on t 8 min read A product array puzzle | Set 2 (O(1) Space) Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator and in O(n). Example: Input: arr[] = {10, 3, 5, 6, 2}Output: prod[] = {180, 600, 360, 300, 900}The elements of output array are {3*5*6*2, 10*5*6* 10 min read Lucky alive person in a circle | Code Solution to sword puzzle Given n people standing in a circle where 1st has a sword, find the luckiest person in the circle, if, from 1st soldier who is has a sword each has to kill the next soldier and handover the sword to next soldier, in turn, the soldier will kill the adjacent soldier and handover the sword to next soldier such that one soldier remains in this war who 7 min read A Sum Array Puzzle Given an array arr[] of n integers, construct a Sum Array sum[] (of same size) such that sum[i] is equal to the sum of all the elements of arr[] except arr[i]. Solve it without subtraction operator and in O(n). Examples: Input : arr[] = {3, 6, 4, 8, 9} Output : sum[] = {27, 24, 26, 22, 21} Input : arr[] = {4, 5, 7, 3, 10, 1} Output : sum[] = {26, 2 15 min read

Article Tags :

  • Branch and Bound
  • DSA
8 puzzle Problem - GeeksforGeeks (2024)

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Rubie Ullrich

Last Updated:

Views: 6168

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.