The Attack of Knight CodeChef Solution

Problem -The Attack of Knight CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

The Attack of Knight CodeChef Solution in C++17

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

using p = vector<pair<int,int>>;

p allowedPositions(int x, int y){
    
    p v {{x-2,y+1},{x-2,y-1},{x-1,y-2},{x+1,y-2},
                  {x+2,y-1},{x+2,y+1},{x+1,y+2},{x-1,y+2}};
    //remove invalid points
    auto z= remove_if(v.begin(),v.end(),[&](auto A ){
        auto &[x,y]=A;
        return (x<1||y<1||x>8||y>8);});
    v.erase(z,v.end());
    return v;
}

bool commonPoint(p&& A, p&& B) {
    bool res=false;
    for (auto e : A){
        auto& [x1,y1] =e;
        for (auto f: B){
            auto& [x2,y2] =f;
            res |=(x1==x2 && y1==y2);}
    }
    return res;
}

int main() {
	int T;
	cin >>T;
	while (T--){
	    int X1,Y1,X2,Y2;
	    cin >> X1 >> Y1 >>X2>> Y2;
	    cout << (commonPoint(allowedPositions(X1,Y1),allowedPositions(X2,Y2))?"Yes\n":"No\n");
	    
	}
	return 0;
}

The Attack of Knight CodeChef Solution in C++14

#include <iostream>
#include<cstdlib>
using namespace std;


int main() 
{
    
int t;
cin>>t;

while(t--)
{
int n,i,j,t,x1,x2,y1,y2,count=0;
int arr[9][9];    
 cin>>x1>>y1;
 cin>>x2>>y2;
 
for(i=0;i<=8;i++)
 {                  //initializing to prevent garbage values
for(j=0;j<=8;j++)
 {
  arr[i][j]=0;   
 }
 }
   
 for(i=-2;i<=2;i++)
 {
 for(j=-2;j<=2;j++)
 {
 if(abs(i*j)==2 && x1+i>=1 && x1+i<=8 && y1+j>=1 && y1+j<=8)     //marking the territory of knight1
    arr[x1+i][y1+j]=1;   
 }
 }
 

 for(i=-2;i<=2;i++)
 {
 for(j=-2;j<=2;j++)
 {
 if(abs(i*j)==2 && x2+i>=1 && x2+i<=8 && y2+j>=1 && y2+j<=8)     //marking the territory of knight2
    arr[x2+i][y2+j]=arr[x2+i][y2+j]+5;   
 }
 }
 
 
 
 
 
 for(i=-2;i<=2;i++)
 {
 for(j=-2;j<=2;j++)
 {
 if(abs(i*j)==2 && x1+i>=1 && x1+i<=8 && y1+j>=1 && y1+j<=8) //checking for common territory
   {    
    if(arr[x1+i][y1+j]==6) 
     count=1;
   }
 }
 }
 
 
  if(count==1)
  cout<<"yes"<<endl;
  else
  cout<<"no"<<endl;
 
 
}



return 0;
}

The Attack of Knight CodeChef Solution in PYTH 3

def isCorner(r,c):
    if r == 1 or r == 8:
        if c == 1 or c == 8:
            return True
        else:
            return False
    else:
        return False
        

T = int(input())

for i in range(T):
    X1,Y1 = [int(n) for n in input().split()]
    X2,Y2 = [int(n) for n in input().split()]
    if (X1 == X2 and abs(Y1-Y2) == 2) or (Y1 == Y2 and abs(X1-X2) == 2):
        print("YES")
        continue
    elif (X1 == X2 and abs(Y1-Y2) == 4) or (Y1 == Y2 and abs(X1-X2) == 4):
        print("YES")
        continue
    elif (abs(X1-X2) == 2 and abs(Y1-Y2) == 4) or (abs(Y1-Y2) == 2 and abs(X1-X2) == 4):
        print("YES")
        continue
    elif (abs(X1-X2) == 1 and abs(Y1-Y2) == 3) or (abs(Y1-Y2) == 1 and abs(X1-X2) == 3):
        print("YES")
        continue
    elif abs(X1-X2) == 3 and abs(Y1-Y2) == 3:
        print("YES")
        continue
    elif abs(X1-X2) == 1 and abs(Y1-Y2) == 1:
        if isCorner(X1,Y1) == False and isCorner(X2,Y2) == False:
            print("YES")
        else:
            print("NO")
    else:
        print("NO")

The Attack of Knight CodeChef Solution in C

#include <stdio.h>
struct pos {
    int x;
    int y;
};

void calculate_knight_positions (struct pos w1, struct pos *pos1)
{
    pos1[0].x = w1.x - 1, pos1[0].y = w1.y - 2;
    pos1[1].x = w1.x - 2, pos1[1].y = w1.y - 1;
    pos1[2].x = w1.x - 1, pos1[2].y = w1.y + 2;
    pos1[3].x = w1.x - 2, pos1[3].y = w1.y + 1;
    pos1[4].x = w1.x + 1, pos1[4].y = w1.y - 2;
    pos1[5].x = w1.x + 2, pos1[5].y = w1.y - 1;
    pos1[6].x = w1.x + 1, pos1[6].y = w1.y + 2;
    pos1[7].x = w1.x + 2, pos1[7].y = w1.y + 1;
}

int main (void)
{
    int test_cases, i, j, found;
    struct pos w1, w2, pos1[8], pos2[8];

    scanf("%d", &test_cases);

    while (test_cases--) {
        scanf("%d %d", &(w1.x), &(w1.y));
        scanf("%d %d", &(w2.x), &(w2.y));

        calculate_knight_positions(w1, pos1);
        calculate_knight_positions(w2, pos2);

        found = 0;
        for (i = 0; i < 8; i++) {
            if ((pos1[i].x < 1) || (pos1[i].x > 8) ||
                (pos1[i].y < 1) || (pos1[i].y > 8)) {
                continue;
            }
            for (j = 0; j < 8; j++) {
                if ((pos2[j].x < 1) || (pos2[j].x > 8) ||
                    (pos2[j].y < 1) || (pos2[j].y > 8)) {
                    continue;
                }
                if ((pos1[i].x == pos2[j].x) && 
                    (pos1[i].y == pos2[j].y)) {
                    found = 1;
                    break;
                }
            }
        }

        if (found == 1) {
            printf("YES\n");
        } else {
            printf("NO\n");
        }
    }
	return 0;
}

The Attack of Knight CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
    public static ArrayList<ArrayList<Integer>> finds(int fx,int fy){
        ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
		    
		    if(fx-2>=1){
		        if(fy-1>=1){
		            ArrayList temp=new ArrayList<>();
		            temp.add(fx-2);
		            temp.add(fy-1);
		            list.add(temp);
		        }
		        if(fy+1<=8){
		            ArrayList temp=new ArrayList<>();
		            temp.add(fx-2);
		            temp.add(fy+1);
		            list.add(temp);
		        }
		        
		    }
		    if(fx+2<=8){
		        if(fy-1>=1){
		            ArrayList temp=new ArrayList<>();
		            temp.add(fx+2);
		            temp.add(fy-1);
		            list.add(temp);
		        }
		         if(fy+1<=8){
		             ArrayList temp=new ArrayList<>();
		            temp.add(fx+2);
		            temp.add(fy+1);
		            list.add(temp);
		        }
		    }
		    if(fy-2>=1){
		        if(fx-1>=1){
		            ArrayList temp=new ArrayList<>();
		            temp.add(fx-1);
		            temp.add(fy-2);
		            list.add(temp);
		        }
		        if(fx+1<=8){
		            ArrayList temp=new ArrayList<>();
		            temp.add(fx+1);
		            temp.add(fy-2);
		            list.add(temp);
		        }
		    }
		    if(fy+2<=8){
		        if(fx-1>=1){
		            ArrayList temp=new ArrayList<>();
		            temp.add(fx-1);
		            temp.add(fy+2);
		            list.add(temp);
		        }
		        if(fx+1<=8){
		            ArrayList temp=new ArrayList<>();
		            temp.add(fx+1);
		            temp.add(fy+2);
		            list.add(temp);
		        }
		    }
		    return list;
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0){
		    int fx=sc.nextInt();
		    int fy=sc.nextInt();
		    int sx=sc.nextInt();
		    int sy=sc.nextInt();
		    ArrayList<ArrayList<Integer>> f=finds(fx,fy);
		    ArrayList<ArrayList<Integer>> s=finds(sx,sy);
		    HashSet<ArrayList<Integer>> h=new HashSet<>();
		    for(ArrayList<Integer> l:f){
		        h.add(l);
		    }
		  //  for(ArrayList<Integer> l:h){
		  //      System.out.println(l.toString());
		  //  }
		  //  System.out.println("--");
		  //  for(ArrayList<Integer> l:s){
		  //      System.out.println(l.toString());
		  //  }
		    boolean truth=false;
		    for(ArrayList<Integer> l:s){
		        if(h.contains(l)){
		            truth=true;
		            break;
		        }
		    }
		    if(truth){
		        System.out.println("Yes");
		      }
		    else{
		        System.out.println("No");
		      }
		}
	}
}

The Attack of Knight CodeChef Solution in PYPY 3

def get_knight_pos(x, y):
    p = set()
    if x-1>0 and y-2>0:
        p.add((x-1, y-2))
    if x-1>0 and y+2<9:
        p.add((x-1, y+2))
    if x+1<9 and y-2>0:
        p.add((x+1, y-2))
    if x+1<9 and y+2<9:
        p.add((x+1, y+2))
    
    if y-1>0 and x-2>0:
        p.add((x-2, y-1))
    if y-1>0 and x+2<9:
        p.add((x+2, y-1))
    if y+1<9 and x-2>0:
        p.add((x-2, y+1))
    if y+1<9 and x+2<9:
        p.add((x+2, y+1))
    
    return p

try:
    T = int(input().strip())
    for _ in range(T):
        # print(_)
        x1, y1 = map(int, input().strip().split(' '))
        x2, y2 = map(int, input().strip().split(' '))
        
        p1 = get_knight_pos(x1, y1)
        p2 = get_knight_pos(x2, y2)
        # print(p1, p2)
        print('YES') if p1.intersection(p2) else print('NO')

except Exception as e:
    print(e)

The Attack of Knight CodeChef Solution in PYTH

L = [[2,1],[2,-1],[-2,1],[-2,-1],[1,2],[1,-2],[-1,2],[-1,-2]]
t = int(raw_input())
for i in range(t):
	st = raw_input().split()
	X1 = int(st[0])
	Y1 = int(st[1])
	st = raw_input().split()
	X2 = int(st[0])
	Y2 = int(st[1])
	S = set()
	for w in L:
		x = X1+w[0]
		y = Y1+w[1]
		if (x in range(1,9)) and (y in range(1,9)):
			n = 10*y+x
			S.add(n)
		# endif
	# endfor w
	valid = False
	for w in L:
		x = X2+w[0]
		y = Y2+w[1]
		if (x in range(1,9)) and (y in range(1,9)):
			n = 10*y+x
			if n in S:
				valid = True
			# endif
		# endif
	# endfor w
	if valid:
		print 'YES'
	else:
		print 'NO'
	# endif
# endfor i

The Attack of Knight CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace ConsoleApp5
{
    internal class Test
    {

        static int abs(int x)
        {
            if (x < 0) return -x;
            return x;
        }

        static bool IsAttacking(int x, int y, int x1, int y1)
        {
            if (abs(x - x1) == 1 && abs(y - y1) == 2)
            {
                return true;
            }
            else if (abs(x - x1) == 2 && abs(y - y1) == 1)
            {
                return true;
            }
            return false;
        }

        static bool Solve(int x1, int y1, int x2, int y2)
        {
            for (int x = 1; x <= 8; x++)
            {
                for (int y = 1; y <= 8; y++)
                {
                    if(IsAttacking(x, y, x1, y1) && IsAttacking(x, y, x2, y2))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        static void Main(string[] args)
        {
            int T = int.Parse(Console.ReadLine());
            for (int i = 0; i < T; i++)
            {
                int[] XY1 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                int[] XY2 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                if (Solve(XY1[0], XY1[1], XY2[0], XY2[1]))
                {
                    Console.WriteLine("Yes");
                }
                else
                {
                    Console.WriteLine("No");
                }
            }
        }
    }
}

The Attack of Knight CodeChef Solution in NODEJS

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const t = parseInt(arr.shift());
  for (let i = 0; i < 2 * t; ) {
    const [x1, y1] = arr[i++].split(" ").map((el) => parseInt(el));
    const [x2, y2] = arr[i++].split(" ").map((el) => parseInt(el));

    const set1 = new Set();
    addToSet(set1, x1 + 1, y1 - 2);
    addToSet(set1, x1 - 1, y1 - 2);
    addToSet(set1, x1 + 2, y1 - 1);
    addToSet(set1, x1 + 2, y1 + 1);
    addToSet(set1, x1 - 2, y1 - 1);
    addToSet(set1, x1 - 2, y1 + 1);
    addToSet(set1, x1 + 1, y1 + 2);
    addToSet(set1, x1 - 1, y1 + 2);

    // console.log(set1);

    const set2 = new Set();
    addToSet(set2, x2 + 1, y2 - 2);
    addToSet(set2, x2 - 1, y2 - 2);
    addToSet(set2, x2 + 2, y2 - 1);
    addToSet(set2, x2 + 2, y2 + 1);
    addToSet(set2, x2 - 2, y2 - 1);
    addToSet(set2, x2 - 2, y2 + 1);
    addToSet(set2, x2 + 1, y2 + 2);
    addToSet(set2, x2 - 1, y2 + 2);

    // console.log(set2);

    const mergeSet = new Set([...set1, ...set2]);

    // console.log(mergeSet);

    if (mergeSet.size < set1.size + set2.size) console.log("YES");
    else console.log("NO");
  }
});

function addToSet(set, x, y) {
  if (x > 8 || y > 8 || x < 1 || y < 1) return;
  set.add(x + "," + y);
}

The Attack of Knight CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		first := readNNums(reader, 2)
		second := readNNums(reader, 2)
		res := solve(first, second)
		if res {
			buf.WriteString("YES\n")
		} else {
			buf.WriteString("NO\n")
		}
	}
	fmt.Print(buf.String())
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func solve(first []int, second []int) bool {
	for x := 1; x <= 8; x++ {
		for y := 1; y <= 8; y++ {
			// place knight at pos (x, y)
			if attack([]int{x, y}, first) && attack([]int{x, y}, second) {
				return true
			}
		}
	}
	return false
}

func attack(knight []int, enemy []int) bool {
	dx := abs(knight[0] - enemy[0])
	dy := abs(knight[1] - enemy[1])

	return dx == 1 && dy == 2 || dx == 2 && dy == 1
}

func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}
The Attack of Knight CodeChef Solution Review:

In our experience, we suggest you solve this The Attack of Knight CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the The Attack of Knight CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this The Attack of Knight CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *