KnightL on a Chessboard


Problem Statement :


KnightL is a chess piece that moves in an L shape. We define the possible moves of  as any movement from some position  to some  satisfying either of the following:


Note that  and  allow for the same exact set of movements. For example, the diagram below depicts the possible locations that  or  can move to from its current location at the center of a  chessboard:


Observe that for each possible movement, the Knight moves  units in one direction (i.e., horizontal or vertical) and  unit in the perpendicular direction.


Input Format

A single integer denoting .

Constraints

Output Format

Print exactly  lines of output in which each line  (where ) contains  space-separated integers describing the minimum number of moves  must make for each respective  (where ). If some  cannot reach position , print -1 instead.



Solution :



title-img


                            Solution in C :

In  C++  :






#include<bits/stdc++.h>

using namespace std;

const int BIG = 2e9;
int n, d[50][50];

void can(queue<pair<int, int>> &q, int i, int j, int dd){
    if(i >= 0 && i < n && j >= 0 && j < n && d[i][j] > dd){
        d[i][j] = dd;
        q.push({i, j});
    }
}

int bfs(int n, int a, int b){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            d[i][j] = BIG;
        }
    }

    d[0][0] = 0;
    queue<pair<int, int>> q;
    q.push({0, 0});
    while(!q.empty()){
        pair<int, int> v = q.front();
        q.pop();
        int x = v.first;
        int y = v.second;
        int dist = d[x][y] + 1;
        can(q, x + a, y + b, dist);
        can(q, x + a, y - b, dist);
        can(q, x - a, y + b, dist);
        can(q, x - a, y - b, dist);
        can(q, x + b, y + a, dist);
        can(q, x + b, y - a, dist);
        can(q, x - b, y + a, dist);
        can(q, x - b, y - a, dist);
    }
    int ans = d[n - 1][n - 1];
    if(ans == BIG){
        return -1;
    }
    return ans;
}

int main(){
    cin >> n;
    for(int i = 1; i < n; i++){
        for(int j = 1; j < n; j++){
            cout << bfs(n, i, j) << " ";
        }
        cout << "\n";
    }
}










In   Java  :







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

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        // your code goes here
        int[][] results = new int[n-1][n-1];
        
        for(int i = 1; i < n; i++){ //decres i and j when entering
            for(int j = 1; j < n; j++){
                int[][] T = new int[n][n];
                Queue<Tupel> q = new LinkedList<Tupel>();
                q.add(new Tupel(0,0));
                while(!q.isEmpty()){
                    Tupel t = q.remove();
                    
                    if(t.x == 0 && t.y == 0){
                        T[0][0] = 1;
                        
                    }
                    
                    if(t.x-i >= 0 && t.y-j >= 0 && T[t.x-i][t.y-j] == 0){
                        T[t.x-i][t.y-j] = T[t.x][t.y]+1;
                        q.add(new Tupel(t.x-i, t.y-j));
                    }
                        
                    if(t.x-j >= 0 && t.y-i >= 0 && T[t.x-j][t.y-i] == 0){
                        T[t.x-j][t.y-i] = T[t.x][t.y]+1;
                        q.add(new Tupel(t.x-j, t.y-i));
                    }
                        
                    if(t.x-i >= 0 && t.y+j < n && T[t.x-i][t.y+j] == 0){
                        T[t.x-i][t.y+j] = T[t.x][t.y]+1;
                        q.add(new Tupel(t.x-i, t.y+j));
                    }    
                        
                    if(t.x-j >= 0 && t.y+i < n && T[t.x-j][t.y+i] == 0){
                        T[t.x-j][t.y+i] = T[t.x][t.y]+1;
                        q.add(new Tupel(t.x-j, t.y+i));
                    }
                        
                    if(t.x+i < n && t.y+j < n && T[t.x+i][t.y+j] == 0){
                        T[t.x+i][t.y+j] = T[t.x][t.y]+1;
                        if(t.x+i == n-1 && t.y+j == n-1){
                            break;
                        }
                        q.add(new Tupel(t.x+i, t.y+j));
                    }
                        
                    if(t.x+j < n && t.y+i < n && T[t.x+j][t.y+i] == 0){
                        T[t.x+j][t.y+i] = T[t.x][t.y]+1;
                        if(t.x+i == n-1 && t.y+j == n-1){
                            break;
                        }
                        q.add(new Tupel(t.x+j, t.y+i));
                    }
                        
                    if(t.x+i < n && t.y-j >= 0 && T[t.x+i][t.y-j] == 0){
                        T[t.x+i][t.y-j] = T[t.x][t.y]+1;
                        q.add(new Tupel(t.x+i, t.y-j));
                    }
                        
                    if(t.x+j < n && t.y-i >= 0 && T[t.x+j][t.y-i] == 0){
                        T[t.x+j][t.y-i] = T[t.x][t.y]+1;
                        q.add(new Tupel(t.x+j, t.y-i));
                    }
                       
                }
                
                results[i-1][j-1] = T[n-1][n-1]-1;
            }
        }
        
        for(int i = 0; i < n-1; i++){
            for(int j = 0; j < n-1; j++){
                System.out.print(results[i][j] + " ");
            }
            System.out.println();
        }
    }
    
}

class Tupel{
    int x;
    int y;
    public Tupel(int x, int y){
        this.x = x;
        this.y = y;
    }
}










In  C  :








#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int n; 
int **checked;

typedef struct node{
    int i;
    int j;
    int g;
    int h;
    struct node *next;
}node_t;

node_t *head = NULL;
node_t *tail = NULL;


void insert(int i, int j, int g, int h){
    if(checked[i][j]==1) return;
    //printf("Insert: %d %d\n",i,j);
    checked[i][j] = 1;
    node_t *newnode = (node_t*)malloc(sizeof(node_t));
    newnode->i = i;
    newnode->j = j;
    newnode->g = g;
    newnode->h = h;
    newnode->next = NULL;
    if(head==NULL){
        head=newnode;
    }
    else{
        tail->next=newnode;
    }
    tail=newnode;
}

int isEmpty(){
    if(head==NULL){
        return 1;
    }
    else return 0;
}

node_t *dequeue(){
    node_t *ret;
    ret = head;
    head = head->next;
    return ret;
}

void testone(int i, int j,int g){
    if(i<0) return;
    if(i>=n) return;
    if(j<0) return;
    if(j>=n) return;
    
    insert(i,j,g,0);
}

void initchecked(){
    int i,j;
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            checked[i][j] = 0;
        }
    }
}

void Astro(int a, int b){
    node_t *node;
    
    tail = NULL;
    head = NULL;
    
    initchecked();
    insert(0,0,0,0);
    while(!isEmpty()){
        node = dequeue();
        //printf("Test: %d %d\n",node->i, node->j);
        if(node==NULL){
            printf("-1 ");
            return ;
        }
        else if(node->i==n-1 && node->j==n-1){
            printf("%d ",node->g);
            return ;
        }
        
        testone(node->i - b, node->j + a, node->g+1);
        testone(node->i - a, node->j + b, node->g+1);
        testone(node->i + a, node->j + b, node->g+1);
        testone(node->i + b, node->j + a, node->g+1);
        
        
        testone(node->i - b, node->j - a, node->g+1);
        testone(node->i - a, node->j - b, node->g+1);
        testone(node->i + a, node->j - b, node->g+1);
        testone(node->i + b, node->j - a, node->g+1);
    }
    printf("-1 ");
}

int main(){
    scanf("%d",&n);
    checked = (int **)malloc(n*sizeof(int *));
    for(int i=0; i<n; i++){
        checked[i] = (int *)malloc(n*sizeof(int *));
    }
    
    for(int i=1; i<=n-1; i++){
        for(int j=1; j<=n-1; j++){
            Astro(i,j);
        }
        printf("\n");
    }
    return 0;
}








In  Python3 :








#!/bin/python3

import sys


n = int(input().strip())
# your code goes here
A=[]
for a in range(1,n):
    B=[]
    for b in range(1,n):
        P={(0,0)}
        c=0
        f=True
        V=set()
        while f:
            c+=1
            Q=set()
            
            V=V|P
            for p in P:
                if (p[0]==n-1)&(p[1]==n-1):
                    f=False
                    break
                if (0<=p[0]+a<n)&(0<=p[1]+b<n):
                    Q.add((p[0]+a,p[1]+b))
                if (0<=p[0]-a<n)&(0<=p[1]-b<n):
                    Q.add((p[0]-a,p[1]-b))
                if (0<=p[0]-a<n)&(0<=p[1]+b<n):
                    Q.add((p[0]-a,p[1]+b))
                if (0<=p[0]+a<n)&(0<=p[1]-b<n):
                    Q.add((p[0]+a,p[1]-b))       
                    
                if (0<=p[0]+b<n)&(0<=p[1]+a<n):
                    Q.add((p[0]+b,p[1]+a))
                if (0<=p[0]-b<n)&(0<=p[1]-a<n):
                    Q.add((p[0]-b,p[1]-a))
                if (0<=p[0]-b<n)&(0<=p[1]+a<n):
                    Q.add((p[0]-b,p[1]+a))
                if (0<=p[0]+b<n)&(0<=p[1]-a<n):
                    Q.add((p[0]+b,p[1]-a))                    

                    
            
            P=set()
            P=P|Q
            P=P-V
            if len(P)==0:
                break
        if not f:
            B.append(c-1)
        else:
            B.append(-1)
    A.append(B)
for a in A:
    for b in a:
        print(b,end= " ")
    print("")
                        








View More Similar Problems

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →