In this HackerRank Gena Playing Hanoi problem solution, we have given a Hanoi tower that has 4 rods and n disks ordered by ascending size. and we also given the state of Hanoi and need to determine the minimum number of moves needed to restore the tower to its original state with all disks on rod first.

HackerRank Gena Playing Hanoi problem solution


Problem solution in Python.

from collections import deque

def tuplify(x):
    return tuple(tuple(i) for i in x)

def moves(rods):
    for x in range(4):
        if rods[x]:
            for y in range(4):
                if not rods[y] or rods[y][-1] > rods[x][-1]:
                    yield (x, y)

def do_move(rods, x, y):
    rods = [list(r) for r in rods]
    rods[y].append(rods[x].pop())
    rods[1:4] = sorted(rods[1:4], key=lambda t: t[-1] if t else 0)
    return tuplify(rods)

def bfs(rods, n):
    start = (tuplify(rods), 0)
    visited = set()
    visited.add(start)
    q = deque([start])
    while q:
        cur, depth = q.popleft()
        if all(len(r) == 0 for r in cur[1:]):
            return depth
        for x, y in moves(cur):
            child = do_move(cur, x, y)
            if child not in visited:
                visited.add(child)
                q.append((child, depth + 1))
    return -1

n = int(input())
rods = [[] for _ in range(4)]
for i, disk in enumerate(map(int, input().split())):
    rods[disk-1] = [i] + rods[disk-1]
print(bfs(rods, n))

{"mode":"full","isActive":false}


Problem solution in Java.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {



    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int ndisc = scan.nextInt();
        int start = 0;
        for (int h = 1; h <= ndisc; ++h) {
            int rod = scan.nextInt();
            --rod;
            start = move(start, rod, h);

        }
        scan.close();
       
        System.out.print(solve(ndisc, start));
    }

    private static int move(int state, int rod, int disc) {
        return (state & ~(3 << 2 * (disc - 1))) | rod << 2 * (disc - 1);
    }

    private static int getDisc(int ndisc, int state, int rod) {

        int disc = ndisc + 1;
        for (int h = ndisc; h != 0; --h) {
            int r = 3 & state >> 2 * (h - 1);
            if (r == rod) {
                disc = h;
            }
        }
        return disc;
    }

    private static long solve(int ndisc, int start) {
        final int win = 0;
        if (start == win) {
            return 0;
        }
        LinkedList<Integer> bfs = new LinkedList<>();
        bfs.addLast(start);
        List<Integer> depth = Arrays.asList(new Integer[1 << 2 * ndisc]);
        depth.set(start, 0);
        while (true) {
            int par = bfs.getFirst();
            bfs.removeFirst();
            int[] d = new int[4];
            for (int rod = 0; rod < 4; ++rod) {
                d[rod] = getDisc(ndisc, par, rod);
            }
            for (int from = 0; from < 4; ++from) {
                if (d[from] == ndisc + 1) {
                    continue;
                }
                for (int to = 0; to < 4; ++to) {
                    if (d[to] > d[from]) {
                        int ch = move(par, to, d[from]);
                        if (ch == win) {
                            return 1 + depth.get(par);
                        }
                        if (depth.get(ch) == null && ch != start) {
                            depth.set(ch, 1 + depth.get(par));
                                                  
                            bfs.addLast(ch);
                        }
                    }
                }
            }
        }

    }
}

{"mode":"full","isActive":false}


Problem solution in C++.

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;

const int Maxn = 10;
const int Inf = 1000000000;

int n;
int dp[1 << 2 * Maxn];

int Get(int mask, int ind)
{
    return (mask & 3 << 2 * ind) >> 2 * ind;    
}

int Set(int mask, int ind, int val)
{
    int got = mask & 3 << 2 * ind;
    mask ^= got;
    mask |= val << 2 * ind;
    return mask;
}

int main(){
    cin >> n;
    fill(dp, dp + (1 << 2 * Maxn), Inf);
    int got = 0;
    for (int i = 0; i < n; i++) {
        int a; scanf("%d", &a); a--;
        got |= a << 2 * i;
    }
    dp[got] = 0;
    queue <int> Q; Q.push(got);
    while (!Q.empty()) {
        int v = Q.front(); Q.pop();
        bool tk[4] = {};
        for (int i = 0; i < n; i++) {
            int my = Get(v, i);
            if (tk[my]) continue;
            for (int j = 0; j < 4; j++) if (my != j && !tk[j]) {
                int u = Set(v, i, j);
                if (dp[v] + 1 < dp[u]) {
                    dp[u] = dp[v] + 1;
                    Q.push(u);
                }
            }
            tk[my] = true;
        }
    }
    printf("%d\n", dp[0]);
    return 0;
}

{"mode":"full","isActive":false}


Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

typedef struct _QueueElement {
    int move;
    int state;
} QueueElement;


int N;


#define QUEUE_SIZE (1024*1024*16)
QueueElement queue[QUEUE_SIZE];
char enqueued[QUEUE_SIZE];
int queueCount = 0;
int queueStart = 0;

int emptyQueue()
{
    return (queueCount == 0);
}


void pushQueue(int move, int state)
{
    int index = queueStart + queueCount;
    if (index >= QUEUE_SIZE) {
        index -= QUEUE_SIZE;
    }
    if (enqueued[state] != move) {
        queue[index].move  = move;
        queue[index].state = state;
        enqueued[state] = move;
        queueCount += 1;
    }
}


int popQueue(int *move)
{
    int res = queue[queueStart].state;
    *move = queue[queueStart].move;
    queueStart += 1;
    if (queueStart >= QUEUE_SIZE) {
        queueStart -= QUEUE_SIZE;
    }
    queueCount -= 1;
    return res;
}


void genMoves(int state, int *moves, int *movesCount)
{
    int rod;
    int i = 0;
    int r[4] = { -1, -1, -1, -1 };
    int tmp = state;
    while (tmp) {
        rod = tmp & 0x3;
        if (r[rod] < 0) {
            r[rod] = i;
        }
        tmp >>= 2;
        i += 1;
    }
    *movesCount = 0;
    if (r[0] >= 0) {
        if (r[0] < r[1] || r[1] < 0) {
            moves[*movesCount] = state | (1 << (r[0] * 2));
            *movesCount += 1;
        }
        if (r[0] < r[2] || r[2] < 0) {
            moves[*movesCount] = state | (2 << (r[0] * 2));
            *movesCount += 1;
        }
        if (r[0] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[0] * 2));
            *movesCount += 1;
        }
    }
    if (r[1] >= 0) {
        if (r[1] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(1 << (r[1] * 2)));
            *movesCount += 1;
        }
        if (r[1] < r[2] || r[2] < 0) {
            moves[*movesCount] = state & (~(1 << (r[1] * 2)));
            moves[*movesCount] |= (2 << (r[1] * 2));
            *movesCount += 1;
        }
        if (r[1] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[1] * 2));
            *movesCount += 1;
        }
    }
    if (r[2] >= 0) {
        if (r[2] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(2 << (r[2] * 2)));
            *movesCount += 1;
        }
        if (r[2] < r[1] || r[1] < 0) {
            moves[*movesCount] = state & (~(2 << (r[2] * 2)));
            moves[*movesCount] |= (1 << (r[2] * 2));
            *movesCount += 1;
        }
        if (r[2] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[2] * 2));
            *movesCount += 1;
        }
    }
    if (r[3] >= 0) {
        if (r[3] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            *movesCount += 1;
        }
        if (r[3] < r[1] || r[1] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            moves[*movesCount] |= (1 << (r[3] * 2));
            *movesCount += 1;
        }
        if (r[3] < r[2] || r[2] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            moves[*movesCount] |= (2 << (r[3] * 2));
            *movesCount += 1;
        }
    }
}


int main()
{
    int i;
    for (i = 0; i < QUEUE_SIZE; ++i) {
        enqueued[i] = -1;
    }
    scanf("%d", &N);
    {
        int state = 0;
        int tmp;
        for (i = 0; i < N; ++i) {
            scanf("%d", &tmp);
            state |= (tmp - 1) << (i * 2);
        }
        pushQueue(0, state);
    }

    {
        int state;
        int move;
        int moves[6];
        int movesCount;

        while (! emptyQueue()) {
            state = popQueue(&move);
            if (! state) {
                break;
            }

            genMoves(state, moves, &movesCount);
            for (i = 0; i < movesCount; ++i) {
                pushQueue(move + 1, moves[i]);
            }
        }

        printf("%d\n", move);
    }

    return 0;
}
                    

{"mode":"full","isActive":false}