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
Contacts
We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co
View Solution →No Prefix Set
There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio
View Solution →Cube Summation
You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor
View Solution →Direct Connections
Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do
View Solution →Subsequence Weighting
A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =
View Solution →Kindergarten Adventures
Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti
View Solution →