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

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →