Red Knight's Shortest Path


Problem Statement :


In ordinary chess, the pieces are only of two colors, black and white. In our version of chess, we are including new pieces with unique movements. One of the most powerful pieces in this version is the red knight.

The red knight can move to six different positions based on its current position (UpperLeft, UpperRight, Right, LowerRight, LowerLeft, Left) as shown in the figure below.


The board is a grid of size . Each cell is identified with a pair of coordinates , where  is the row number and  is the column number, both zero-indexed. Thus,  is the upper-left corner and  is the bottom-right corner.

Complete the function printShortestPath, which takes as input the grid size , and the coordinates of the starting and ending position  and  respectively, as input. The function does not return anything.

Given the coordinates of the starting position of the red knight and the coordinates of the destination, print the minimum number of moves that the red knight has to make in order to reach the destination and after that, print the order of the moves that must be followed to reach the destination in the shortest way. If the destination cannot be reached, print only the word "Impossible".

Note: There may be multiple shortest paths leading to the destination. Hence, assume that the red knight considers its possible neighbor locations in the following order of priority: UL, UR, R, LR, LL, L. In other words, if there are multiple possible options, the red knight prioritizes the first move in this list, as long as the shortest path is still achievable. Check sample input  for an illustration.


Input Format

The first line of input contains a single integer . The second line contains four space-separated integers .  denotes the coordinates of the starting position and  denotes the coordinates of the final position.

Constraints

the starting and the ending positions are different


Output Format

If the destination can be reached, print two lines. In the first line, print a single integer denoting the minimum number of moves that the red knight has to make in order to reach the destination. In the second line, print the space-separated sequence of moves.

If the destination cannot be reached, print a single line containing only the word Impossible.



Solution :



title-img


                            Solution in C :

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  s_action
{
    int         step;
    int         UL;
    int         UR;
    int         R;
    int         LR;
    int         LL;
    int         L;
}               t_action;

void    ft_impossible()
{
    printf("Impossible");
    exit(0);
}

void    init_action(t_action *action)
{
    action->step = 0;
    action->UL = 0;
    action->UR = 0;
    action->R = 0;
    action->LR = 0;
    action->LL = 0;
    action->L = 0;
}
void    UL(int *i_start, int *j_start, t_action *action, int n)
{
    *i_start -= 2;
    *j_start -= 1;
    if (*j_start < 0)
        ft_impossible();
    action->step += 1;
    action->UL += 1;
}

void    UR(int *i_start, int *j_start, t_action *action, int n)
{
    *i_start -= 2;
    *j_start += 1;
    if (*j_start >= n)
        ft_impossible();
    action->step += 1;
    action->UR += 1;
}

void    R(int *j_start, t_action *action, int n)
{
    *j_start += 2;
    if (*j_start >= n)
        ft_impossible();
    action->step += 1;
    action->R += 1;
}

void    LR(int *i_start, int *j_start, t_action *action, int n)
{
    *i_start += 2;
    *j_start += 1;
    if (*j_start >= n)
        ft_impossible();
    action->step += 1;
    action->LR += 1;
}

void    LL(int *i_start, int *j_start, t_action *action, int n)
{
    *i_start += 2;
    *j_start -= 1;
    if (*j_start < 0)
        ft_impossible();
    action->step += 1;
    action->LL += 1;
}

void    L(int *j_start, t_action *action, int n)
{
    *j_start -= 2;
    if (*j_start < 0)
        ft_impossible();
    action->step += 1;
    action->L += 1;
}

void    print_action(t_action action)
{
    printf("%d\n", action.step);
    while (action.UL--)
        printf("UL ");
    while (action.UR--)
        printf("UR ");
    while (action.R--)
        printf("R ");
    while (action.LR--)
        printf("LR ");
    while (action.LL--)
        printf("LL ");
    while (action.L--)
        printf("L ");
}

void printShortestPath(int n, int i_start, int j_start, int i_end, int j_end) {
    //  Print the distance along with the sequence of moves.
    t_action    action;
    int         vertical;
    int         down_move;
    
    init_action(&action);
    vertical = (i_end - i_start > 0) ? i_end - i_start : i_start - i_end;
    if (vertical % 2 == 1)
        ft_impossible();
    while (i_end < i_start)
    {
        if (j_end <= j_start)
            UL(&i_start, &j_start, &action, n);
        else
            UR(&i_start, &j_start, &action, n);
    }
    down_move = vertical / 2 - action.step;
    while (j_end - down_move > j_start)
        R(&j_start, &action, n);
    while (i_end > i_start)
    {
        if (j_end >= j_start)
            LR(&i_start, &j_start, &action, n);
        else
            LL(&i_start, &j_start, &action, n);
    }
    while (j_end < j_start)
        L(&j_start, &action, n);
    if (j_end != j_start)
        ft_impossible();
    print_action(action);
}

int main() {
    int n; 
    scanf("%i", &n);
    int i_start; 
    int j_start; 
    int i_end; 
    int j_end; 
    scanf("%i %i %i %i", &i_start, &j_start, &i_end, &j_end);
    printShortestPath(n, i_start, j_start, i_end, j_end);
    return 0;
}
                        


                        Solution in C++ :

In  C++  :








#include <bits/stdc++.h>

#ifndef LOCAL
#define cerr dolor_sit_amet
#endif

#define mp make_pair
#define sz(x) ((int)((x).size()))
#define X first
#define Y second
#define ALL(x) (x).begin(), (x).end()

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair < int , int > ipair;
typedef pair < ll , ll > lpair;
const int IINF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fll;
const double DINF = numeric_limits<double>::infinity();
const int MOD = 1000000007;
const double EPS = 1e-9;
const double PI = acos(-1.0);
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll sqr(ll x) { return x*x; } ll sqr(int x) { return (ll)x*x; }
double sqr(double x) { return x*x; } ld sqr(ld x) { return x*x; }
mt19937 mmtw(960172);
ll rnd(ll x, ll y) { static uniform_int_distribution<ll> d; return d(mmtw) % (y - x + 1) + x; }

// ========================================================================= //

const int DX[] = {2, 2, 0, -2, -2, 0};
const int DY[] = {-1, 1, 2, 1, -1, -2};
const string DS[] = {"LL", "LR", "R", "UR", "UL", "L"};
const int order[] = {4, 3, 2, 1, 0, 5};

const int N = 222;

int d[N][N], dp[N][N];

int main() {
    ios::sync_with_stdio(false);

    int n;
    int x1, y1, x2, y2;

    cin >> n >> x1 >> y1 >> x2 >> y2;
    memset(d, 0x3f, sizeof(d));
    d[x1][y1] = 0;
    vector<ipair> q = {{x1, y1}};
    for (int i = 0; i < sz(q); ++i) {
        int x = q[i].X, y = q[i].Y;
        for (int j : order) {
            int nx = x + DX[j];
            int ny = y + DY[j];
            if (nx >= 0 && ny >= 0 && nx < n && ny < n && d[nx][ny] == IINF) {
                d[nx][ny] = d[x][y] + 1;
                dp[nx][ny] = j;
                q.push_back({nx, ny});
            }
        }
    }

    if (d[x2][y2] == IINF)
        cout << "Impossible\n";
    else {
        vector<string> ss;
        while (x2 != x1 || y2 != y1) {
            int j = dp[x2][y2];
            ss.push_back(DS[j]);
            x2 -= DX[j];
            y2 -= DY[j];
        }
        reverse(ALL(ss));
        cout << sz(ss) << "\n";
        for (auto x : ss)
            cout << x << " ";
        cout << "\n";
    }

    return 0;
}
                    


                        Solution in Java :

In  Java :






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

public class Solution {

    static class Node {
        int i, j;
        List<String> movesSoFar = new LinkedList<>();
        
        Node(int i, int j) {
            this.i = i;
            this.j = j;
        }
        
        Node(int i, int j, Node a, String moveTo) {
            this.i = i;
            this.j = j;
            this.movesSoFar.addAll(a.movesSoFar);
            this.movesSoFar.add(moveTo);
        }
    }
    
    static void printShortestPath(int n, int i_start, int j_start, int i_end, int j_end) {
        boolean[][] visited = new boolean[n][n];
        Queue<Node> queue = new LinkedList<>();
        Node start = new Node(i_start, j_start);
        queue.add(start);
        visited[start.i][start.j] = true;
        List<String> path = null;
        while (!queue.isEmpty()) {
            Node current = queue.poll();
            if (current.i == i_end && current.j == j_end) {
                path = current.movesSoFar;
                break;
            }
            
            if (current.j - 1 >= 0 && current.i - 2 >= 0 && !visited[current.i-2][current.j-1]) {
                // UL
                queue.offer(new Node(current.i-2, current.j-1, current, "UL"));
                visited[current.i-2][current.j-1] = true;
            }
            if (current.j + 1 < n && current.i - 2 >= 0 && !visited[current.i-2][current.j+1]) {
                queue.offer(new Node(current.i-2, current.j+1, current, "UR"));
                visited[current.i-2][current.j+1] = true;
            }
            if (current.j + 2 < n && !visited[current.i][current.j+2]) {
                queue.offer(new Node(current.i, current.j+2, current, "R"));
                visited[current.i][current.j+2] = true;
            }
            if (current.i+2 < n && current.j+1 < n && !visited[current.i+2][current.j+1]) {
                queue.offer(new Node(current.i+2, current.j+1, current, "LR"));
                visited[current.i+2][current.j+1] = true;
            }
            if (current.i+2 < n && current.j-1 >= 0 && !visited[current.i+2][current.j-1]) {
                queue.offer(new Node(current.i+2, current.j-1, current, "LL"));
                visited[current.i+2][current.j-1] = true;
            }
            if (current.j-2 >= 0 && !visited[current.i][current.j-2]) {
                queue.offer(new Node(current.i, current.j-2, current, "L"));
                visited[current.i][current.j-2] = true;
            }
        }
        
        if (path != null) {
            System.out.println(path.size());
            boolean first = true;
            for (String item : path) {
                if (!first) {
                    System.out.print(" ");
                }
                System.out.print(item);
                first = false;
            }
            System.out.println();
        } else {
            System.out.println("Impossible");
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int i_start = in.nextInt();
        int j_start = in.nextInt();
        int i_end = in.nextInt();
        int j_end = in.nextInt();
        printShortestPath(n, i_start, j_start, i_end, j_end);
        in.close();
    }
}
                    


                        Solution in Python : 
                            
In   Python3 :









#!/bin/python3

import sys

def printShortestPath(n, i_start, j_start, i_end, j_end):
    #  Print the distance along with the sequence of moves.
    fromdict = {}
    tovisit = [(i_start, j_start)]
    while len(tovisit) > 0:
        i, j = tovisit.pop(0)
        if (i,j) == (i_end, j_end): break
        if i > 1 and j > 0 and (i-2,j-1) not in fromdict:
            tovisit.append((i-2,j-1))
            fromdict[(i-2,j-1)] = ('UL',i,j)
        if i > 1 and j < n-1 and (i-2,j+1) not in fromdict:
            tovisit.append((i-2,j+1))
            fromdict[(i-2,j+1)] = ('UR',i,j)         
        if j < n-2 and (i,j+2) not in fromdict:
            tovisit.append((i,j+2))
            fromdict[(i,j+2)] = ('R',i,j)
        if i < n-2 and j < n-1 and (i+2,j+1) not in fromdict:
            tovisit.append((i+2,j+1))
            fromdict[(i+2,j+1)] = ('LR',i,j)   
        if i < n-2 and j > 0 and (i+2,j-1) not in fromdict:
            tovisit.append((i+2,j-1))
            fromdict[(i+2,j-1)] = ('LL',i,j)
        if j > 1 and (i,j-2) not in fromdict:
            tovisit.append((i,j-2))
            fromdict[(i,j-2)] = ('L',i,j)
    if (i_end, j_end) not in fromdict:
        print("Impossible")
    else:
        ans = []
        i,j = i_end, j_end
        while (i,j) != (i_start,j_start):
            dr, i_n, j_n = fromdict[(i,j)]
            ans.append(dr)
            i,j = i_n, j_n
        ans=ans[::-1]
        print(len(ans))
        print(' '.join(ans))
        

if __name__ == "__main__":
    n = int(input().strip())
    i_start, j_start, i_end, j_end = input().strip().split(' ')
    i_start, j_start, i_end, j_end = [int(i_start), int(j_start), int(i_end), int(j_end)]
    printShortestPath(n, i_start, j_start, i_end, j_end)
                    


View More Similar Problems

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →