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 :
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
2D Array-DS
Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t
View Solution →Dynamic Array
Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.
View Solution →Left Rotation
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d
View Solution →Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun
View Solution →Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →