In this post, we will solve HackerRank Red Knight’s Shortest Path Problem Solution.
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)
The board is a grid of size n x n. Each cell is identified with a pair of coordinates (i, j), where i is the row number and j is the column number, both zero-indexed. Thus, (0, 0) is the upper-left corner and (n-1, n − 1) is the bottom-right corner.
Complete the function printShortest Path, which takes as input the grid size n, and the coordinates of the starting and ending position (i start, İstart) and (iend, Jend) 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 2 for an illustration.
Input Format
The first line of input contains a single integer n. The second line contains four space- separated integers i start, İstart, iend, Jend. (i start, İstart) denotes the coordinates of the starting position and (iend, Jend) denotes the coordinates of the final position.
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
.
Sample Input 0
7 6 6 0 1
Sample Output 0
4 UL UL UL L
Red Knight’s Shortest Path C Solution
#include<stdio.h>
int func(int,int,int,int,int);
int main()
{
int n,sti,stj,eni,enj;
scanf("%d %d %d %d %d",&n,&stj,&sti,&enj,&eni);
func(n,sti,stj,eni,enj);
return 0;
}
int func(int s,int sti,int stj,int eni,int enj)
{
int ar[200],x,y,n,j,i=0;
y=stj-enj;
x=sti-eni;
ar[0]=0;
if(y%2!=0)
{
printf("Impossible");
return 0;
}
if((((y/2)%2==0)&&((x%2==1)||(x%2==-1)))||(((y/2)%2==1||(y/2)%2==-1)&&x%2==0))
{
printf("Impossible");
return 0;
}
if(x>=0&&y>0)
{
if(x<y/2)
{
n=y/2-x;
for(j=0;j<n;j++)
{
if(sti==0)
{
ar[i]=2;
x++;
sti++;
y-=2;
}
else
{
ar[i]=1;
x--;
sti--;
y-=2;
j--;
}
i++;
}
while(y!=0)
{
ar[i]=1;
i++;
x--;
y-=2;
}
}
else
{
//n=(-y/2-x)/2;
//y+=2*n;
for(j=0;j<y/2;j++)
{
ar[i]=1;
i++;
x--;
}
while(x!=0)
{
//printf("%dg",x);
ar[i]=6;
x-=2;
i++;
}
}
}/*
for(j=0;j<(x/2);j++,i++)
ar[i]=6;*/
if(x<=0&&y<=0)
{
if(-x<=-(y/2))
{
n=(-(y/2)+x)/2;
//printf("d%dgh",n);
for(j=0;j<n&&y;j++)
{
//printf("bm%d",y);
if(sti<s-1&&x<-y/2)
{
j--;
ar[i]=4;
//printf("w%d",ar[i]);
i++;
x++;
y+=2;
sti++;
}
//for(j=0;j<n;j++)
else
{
ar[i]=5;
i++;
y+=2;
sti--;
}
}
while(y!=0)
{
ar[i]=4;
i++;
y+=2;
}
}
else if(-x>y/2)
{
for(j=0;j<(-x+y/2)/2;j++)
{
ar[i]=3;
i++;
}
for(j=0;j<-(y/2);j++)
{
ar[i]=4;
i++;
//y+=2;
}
}
}
if(x<0&&y>=0)
{
//printf("ok");
if(-x<(y/2))
{
n=((y/2)+x)/2;
for(j=0;j<n;j++)
{
if(sti==0)
{
j--;
ar[i]=2;
i++;
y-=2;
sti++;
}
//printf("t")
else
{
ar[i]=1;
i++;
y-=2;
sti--;
}
//printf("hi%d",y);
}
while(y!=0)
{
ar[i]=2;
y-=2;
i++;
}
}
else
{
//printf("a%d ",y);
for(j=0;j<y/2;j++)
{
ar[i]=2;
i++;
//y-=2;
x++;
//printf("%db",-x);
}
//x--;
for(j=0;j<-x;j+=2)
{
//printf(" c%dv%d",x,j);
ar[i]=3;
i++;
}
}
}
if(x>0&&y<0&&(x<-y/2))
//for(i=0;i>-1;i++)
//printf("abcd");
{ n=(-y/2-x)/2;
for(j=0;j<n;j++)
{
if(sti!=s-1)
{ sti++;
ar[i]=4;
i++;
y+=2;
}
else
{ sti--;
ar[i]=5;
i++;
j--;
y+=2;
}
}
while(y!=0)
{
ar[i]=5;
i++;
y+=2;
}}/*if(x>0&&sti==n-1)
{
ar[i]=5;
x--;
sti--;
y+=2;
}
else
{
ar[i]=4;
x++;
sti++;
y+=2;
}
i++;
}
if(-x<(y/2))
{
n=(y/2+x)/2;
y-=2*n;
for(i=0;i<n;)
{
ar[i]=1;
i++;
}
}
while(y>0)
{
ar[i]=2;
y-=2;
x--;
i++;
}
for(j=0;j<-(x/2);j++,i++)
ar[i]=3;
}
*/
printf("%d\n",i);
//for(j=0;j<i;j++)
//printf("%d ",ar[j]);
for(j=0;j<i;j++)
switch(ar[j])
{
case 1:
printf("UL ");
break;
case 2:
printf("UR ");
break;
case 3:
printf("R ");
break;
case 4:
printf("LR ");
break;
case 5:
printf("LL ");
break;
case 6:
printf("L ");
break;
default:
printf("Impossible");
}
return 0;
}
Red Knight’s Shortest Path C++ Solution
//By Don4ick
//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
typedef unsigned int ui;
#define forn(i, n) for (int i = 1; i <= n; i++)
#define pb push_back
#define all(x) x.begin(), x.end()
#define y1 qwer1234
const double PI = acos(-1.0);
const int DIR = 6;
const int Y[] = {-1, 1, 2, 1, -1, -2};
const int X[] = {-2, -2, 0, 2, 2, 0};
const int N = 205;
using namespace std;
const string NAMES[] = {"UL", "UR", "R", "LR", "LL", "L"};
int n, x1, y1, x2, y2, d[N][N];
vector < string > ans;
queue < pair < int, int > > q;
bool in(int x, int y)
{
return x >= 0 && x < n && y >= 0 && y < n;
}
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
//cout.tie(NULL);
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
cin >> n >> x1 >> y1 >> x2 >> y2;
for (int i = 0; i < n; i++)
fill(d[i], d[i] + n, -1);
d[x2][y2] = 0;
q.push({x2, y2});
while(!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < DIR; i++)
{
int tx = x + X[i], ty = y + Y[i];
if (in(tx, ty) && d[tx][ty] == -1)
{
d[tx][ty] = d[x][y] + 1;
q.push({tx, ty});
}
}
}
if (d[x1][y1] == -1)
{
cout << "Impossible" << endl;
return 0;
}
int x = x1, y = y1;
while(x != x2 || y != y2)
{
for (int i = 0; i < DIR; i++)
{
int tx = x + X[i], ty = y + Y[i];
if (in(tx, ty) && d[tx][ty] == d[x][y] - 1)
{
ans.pb(NAMES[i]);
x = tx;
y = ty;
break;
}
}
}
cout << (int)ans.size() << endl;
for (auto it : ans)
cout << it << ' ';
return 0;
}
Red Knight’s Shortest Path C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
class Cell
{
public int Row { get; set; }
public int Column { get; set; }
public Cell(int row, int column)
{
Row = row;
Column = column;
}
}
class Program
{
static Cell[,] next;
static int[,] directionCellIndex;
static int[,] jumps;
static List<Cell> directions = new List<Cell>()
{
new Cell(-2, -1),
new Cell(-2, 1),
new Cell(0, 2),
new Cell(2, 1),
new Cell(2, -1),
new Cell(0, -2)
};
//static List<string> directionNames = new List<string>()
//{
// "UL",
// "UR",
// "R",
// "LR",
// "LL",
// "L"
//};
static List<string> mirrorDirectionNames = new List<string>()
{
"LR",
"LL",
"L",
"UL",
"UR",
"R"
};
static List<int> mirrorIndex = new List<int>()
{
3,
4,
5,
0,
1,
2
};
static void printShortestPath(int n, int startRow, int startColumn, int endRow, int endColumn)
{
var startCell = new Cell(startRow, startColumn);
var endCell = new Cell(endRow, endColumn);
directionCellIndex = new int[n, n];
jumps = new int[n, n];
next = new Cell[n, n];
for (int row = 0; row < n; row++)
{
for (int column = 0; column < n; column++)
{
directionCellIndex[row, column] = -1;
jumps[row, column] = int.MaxValue;
next[row, column] = new Cell(-1, -1);
}
}
var toProcess = new List<Cell>();
var currentJumps = 0;
jumps[endRow, endColumn] = 0;
toProcess.Add(new Cell(endRow, endColumn));
while (toProcess.Any())
{
currentJumps++;
var nextToProcess = new List<Cell>();
foreach (var cell in toProcess)
{
for (int directionIndex = 0; directionIndex < directions.Count; directionIndex++)
{
var direction = directions[directionIndex];
var jumpedAtCell = new Cell(cell.Row + direction.Row, cell.Column + direction.Column);
if (jumpedAtCell.Row < 0 || jumpedAtCell.Column < 0 || jumpedAtCell.Row >= n || jumpedAtCell.Column >= n)
{
continue;
}
if (jumps[jumpedAtCell.Row, jumpedAtCell.Column] > currentJumps ||
(jumps[jumpedAtCell.Row, jumpedAtCell.Column] == currentJumps &&
mirrorIndex[directionCellIndex[jumpedAtCell.Row, jumpedAtCell.Column]] > mirrorIndex[directionIndex]))
{
directionCellIndex[jumpedAtCell.Row, jumpedAtCell.Column] = directionIndex;
jumps[jumpedAtCell.Row, jumpedAtCell.Column] = currentJumps;
next[jumpedAtCell.Row, jumpedAtCell.Column] = cell;
nextToProcess.Add(jumpedAtCell);
}
}
}
toProcess.Clear();
toProcess.AddRange(nextToProcess);
}
if (jumps[startRow, startColumn] == int.MaxValue)
{
Console.WriteLine("Impossible");
}
else
{
Console.WriteLine(jumps[startRow, startColumn]);
var nextCell = startCell;
while (nextCell.Row != -1 &&
!(nextCell.Row == endCell.Row && nextCell.Column == endCell.Column))
{
Console.Write($"{mirrorDirectionNames[directionCellIndex[nextCell.Row, nextCell.Column]]} ");
nextCell = next[nextCell.Row, nextCell.Column];
}
}
}
static void printJumps(int[,] jumps, int n)
{
for (int row = 0; row < n; row++)
{
for (int column = 0; column < n; column++)
{
Console.Write(jumps[row, column]);
}
Console.WriteLine();
}
}
static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] tokens_i_start = Console.ReadLine().Split(' ');
int row_start = Convert.ToInt32(tokens_i_start[0]);
int column_start = Convert.ToInt32(tokens_i_start[1]);
int row_end = Convert.ToInt32(tokens_i_start[2]);
int column_end = Convert.ToInt32(tokens_i_start[3]);
printShortestPath(n, row_start, column_start, row_end, column_end);
}
}
}
Red Knight’s Shortest Path Java Solution
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int[] shiftI = {-2, -2, 0, 2, 2, 0};
static int[] shiftJ = {-1, 1, 2, 1, -1, -2};
static String[] let = {"UL", "UR", "R", "LR", "LL", "L"};
static void printShortestPath(int n, int i_start, int j_start, int i_end, int j_end) {
String[][] path = new String[n][n];
int[][] steps = new int[n][n];
path[i_start][j_start] = "";
steps[i_start][j_start] = 0;
int qi[] = new int[40000];
int qj[] = new int[40000];
qi[0] = i_start;
qj[0] = j_start;
int size = 1;
for (int k = 0; k < size; k++)
{
int i = qi[k];
int j = qj[k];
for (int t = 0; t < 6; t++)
{
int ni = i + shiftI[t];
int nj = j + shiftJ[t];
if (ni >= 0 && ni < n && nj >= 0 && nj < n &&
path[ni][nj] == null)
{
path[ni][nj] = (path[i][j].length() == 0 ? let[t] : path[i][j] + " " + let[t]);
steps[ni][nj] = steps[i][j] + 1;
qi[size] = ni;
qj[size] = nj;
size++;
}
}
}
if (path[i_end][j_end] == null)
{
System.out.println("Impossible");
}
else
{
System.out.println(steps[i_end][j_end]);
System.out.println(path[i_end][j_end]);
}
}
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();
}
}
Red Knight’s Shortest Path JavaScript Solution
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function printShortestPath(n, i_start, j_start, i_end, j_end) {
// Print the distance along with the sequence of moves.
var path = r(j_start, i_start, j_end, i_end, []);
if (path.length == 0) {
console.log('Impossible');
} else {
var order = ['UL', 'UR', 'R', 'LR', 'LL', 'L'];
console.log(path.length);
console.log(
path.sort((a,b) => (
order.indexOf(a) - order.indexOf(b)
)).join(' ')
);
}
}
function r(x1, y1, x2, y2, path) {
if (y1 != y2 && Math.abs(y1 - y2) % 2 != 0) {
return [];
}
else if (Math.abs(x1 - x2) % 2 != 0 && y1 == y2) {
return [];
}
if (y1 - y2 > 0) {
if (x1 - x2 >= 0) {
path.push('UL');
return r(x1 - 1, y1 - 2, x2, y2, path);
}
else {
path.push('UR');
return r(x1 + 1, y1 - 2, x2, y2, path);
}
} else if (y2 - y1 > 0) {
if (x1 - x2 >= 0) {
path.push('LL');
return r(x1 - 1, y1 + 2, x2, y2, path);
}
else {
path.push('LR');
return r(x1 + 1, y1 + 2, x2, y2, path);
}
} else if (x1 - x2 > 0) {
path.push('L');
return r(x1 - 2, y1, x2, y2, path);
} else if (x2 - x1 > 0) {
path.push('R');
return r(x1 + 2, y1, x2, y2, path);
}
return path;
}
function main() {
var n = parseInt(readLine());
var i_start_temp = readLine().split(' ');
var i_start = parseInt(i_start_temp[0]);
var j_start = parseInt(i_start_temp[1]);
var i_end = parseInt(i_start_temp[2]);
var j_end = parseInt(i_start_temp[3]);
printShortestPath(n, i_start, j_start, i_end, j_end);
}
Red Knight’s Shortest Path Python Solution
#!/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)