The Attack of Queen Solution Codechef

The Attack of Queen Solution Codechef

Chef has started developing interest in playing chess, and was learning how the Queen moves.

Chef has an empty N×N chessboard. He places a Queen at (X,Y) and wonders – What are the number of cells that are under attack by the Queen?

Notes:

The top-left cell is (1,1), the top-right cell is (1,N), the bottom-left cell is (N,1) and the bottom-right cell is (N,N).
The Queen can be moved any number of unoccupied cells in a straight line vertically, horizontally, or diagonally.
The cell on which the Queen is present, is not said to be under attack by the Queen.

Input Format
The first line contains a single integer T – the number of test cases. Then the test cases follow.
The first and only line of each test case contains three integers N, X and Y, as described in the problem statement.

Output Format
For each test case, output in a single line, the total number of cells that are under attack by the Queen.

Constraints
1≤T≤104
1≤N≤106
1≤X,Y≤N

Sample Input 1
5
1 1 1
3 2 2
3 2 1
2 2 2
150 62 41

Sample Output 1
0
8
6
3
527

Explanation

  • Test case 1: The only cell on the board is (1,1). Since Queen stands on this cell, it is not under attack.
  • Test case 2: The Queen can attack the following cells: {(1,1),(1,2),(1,3),(2,1),(2,3),(3,1),(3,2),(3,3)}.
  • Test case 3: The Queen can attack the following cells: {(1,1),(1,2),(2,2),(2,3),(3,1),(3,2)}.
  • Test case 4: The Queen can attack the following cells: {(1,1),(1,2),(2,1)}.

SOLUTION

Program: The Attack of Queen Solution Codechef in Python

t=int(input())
for i in range(t):
    n,x,y=map(int,input().split())
    q=n-x+x-1+n-y+y-1
    a=min(x-1,y-1)
    b=min(x-1,n-y)
    c=min(n-x,y-1)
    d=min(n-x,n-y)
    print(q+a+b+c+d)

Program: The Attack of Queen Solution Codechef in C++

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        long n,x,y;
        cin>>n>>x>>y;
        cout<<2*n-2 +
        min(abs(1-x),(abs(1-y)))+
        min(abs(n-x),(abs(n-y)))+
        min(abs(1-x),(abs(n-y)))+
        min(abs(n-x),(abs(1-y)));
        cout<<endl;
            
    }
    return 0;
}

Program: The Attack of Queen Solution Codechef in Java

import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{ 	public static void main (String[] args) throws java.lang.Exception
	{
	Scanner sc=new Scanner(System.in);
	int t=sc.nextInt();
	for(int i=0;i<t;i++){
	    int n=sc.nextInt();
	    int x=sc.nextInt();
	    int y=sc.nextInt();
	    
	    int sum=2*(n-1);
	    sum=sum+Math.min(x,y)+Math.min(n-x,n-y);
	    sum=sum+Math.min(x-1,n-y)+Math.min(y-1,n-x);
	    
	    System.out.println(sum-1);
	    
	}
	}
        
    }

Related:

Leave a Comment

eleven − 7 =