Given pair of coordinates of K rooks on an N X N chessboard, the task is to count the number of rooks that can attack each other. Note: 1 <= K <= N*N
Examples:
Input: K = 2, arr[][] = { {2, 2}, {2, 3} }, N = 8
Output: 2
Explanation: Both the rooks can attack each other, because they are in the same row. Therefore, count of rooks that can attack each other is 2
Input: K = 1, arr[][] = { {4, 5} }, N = 4
Output: 0
Approach: The task can easily be solved using the fact that, 2 rooks can attack each other if they are either in the same row or in the same column, else they can’t attack each other.
Below is the implementation of the above code:
C++
#include <bits/stdc++.h>
using namespace std;
int willAttack(vector<vector< int > >& arr, int k, int N)
{
int ans = 0;
for ( int i = 0; i < k; i++) {
for ( int j = 0; j < k; j++) {
if (i != j) {
if ((arr[i][0] == arr[j][0])
|| (arr[i][1] == arr[j][1]))
ans++;
}
}
}
return ans;
}
int main()
{
vector<vector< int > > arr = { { 2, 2 }, { 2, 3 } };
int K = 2, N = 8;
cout << willAttack(arr, K, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class Solution {
static int willAttack( int arr[][], int k, int N)
{
int ans = 0 ;
for ( int i = 0 ; i < k; i++) {
for ( int j = 0 ; j < k; j++) {
if (i != j) {
if ((arr[i][ 0 ] == arr[j][ 0 ])
|| (arr[i][ 1 ] == arr[j][ 1 ]))
ans++;
}
}
}
return ans;
}
public static void main(String[] args)
{
int [][] arr = { { 2 , 2 }, { 2 , 3 } };
int K = 2 , N = 8 ;
System.out.println(willAttack(arr, K, N));
}
}
|
Python3
def willAttack(arr, k, N):
ans = 0
for i in range ( 0 , k):
for j in range ( 0 , k):
if (i ! = j):
if ((arr[i][ 0 ] = = arr[j][ 0 ])
or (arr[i][ 1 ] = = arr[j][ 1 ])):
ans + = 1
return ans
if __name__ = = "__main__" :
arr = [[ 2 , 2 ], [ 2 , 3 ]]
K = 2
N = 8
print (willAttack(arr, K, N))
|
C#
using System;
class Solution
{
static int willAttack( int [,] arr, int k, int N)
{
int ans = 0;
for ( int i = 0; i < k; i++)
{
for ( int j = 0; j < k; j++)
{
if (i != j)
{
if ((arr[i, 0] == arr[j, 0])
|| (arr[i, 1] == arr[j, 1]))
ans++;
}
}
}
return ans;
}
public static void Main()
{
int [,] arr = { { 2, 2 }, { 2, 3 } };
int K = 2, N = 8;
Console.WriteLine(willAttack(arr, K, N));
}
}
|
Javascript
<script>
function willAttack(arr, k, N) {
let ans = 0;
for (let i = 0; i < k; i++) {
for (let j = 0; j < k; j++) {
if (i != j) {
if ((arr[i][0] == arr[j][0])
|| (arr[i][1] == arr[j][1]))
ans++;
}
}
}
return ans;
}
let arr = [[2, 2], [2, 3]];
let K = 2, N = 8;
document.write(willAttack(arr, K, N));
</script>
|
Time Complexity: O(K*K)
Auxiliary Space: O(1)