在 N*N 棋盘上放置的 K 个车中可以互相攻击的车的数量
给定NXN棋盘上K车的坐标对,任务是计算可以互相攻击的车的数量。注意: 1 <= K <= N*N
例子:
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
方法:使用以下事实可以轻松解决任务,如果两个车在同一行或同一列,则可以互相攻击,否则它们不能互相攻击。
下面是上述代码的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count the number of attacking rooks
int willAttack(vector >& 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) {
// Check if rooks are in same row
// or same column
if ((arr[i][0] == arr[j][0])
|| (arr[i][1] == arr[j][1]))
ans++;
}
}
}
return ans;
}
// Driver Code
int main()
{
vector > 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) {
// Check if rooks are in same row
// or same column
if ((arr[i][0] == arr[j][0])
|| (arr[i][1] == arr[j][1]))
ans++;
}
}
}
return ans;
}
// Driver code
public static void main(String[] args)
{
int[][] arr = { { 2, 2 }, { 2, 3 } };
int K = 2, N = 8;
System.out.println(willAttack(arr, K, N));
}
}
// This code is contributed by dwivediyash.
Python3
# python program for the above approach
# Function to count the number of attacking rooks
def willAttack(arr, k, N):
ans = 0
for i in range(0, k):
for j in range(0, k):
if (i != j):
# Check if rooks are in same row
# or same column
if ((arr[i][0] == arr[j][0])
or (arr[i][1] == arr[j][1])):
ans += 1
return ans
# Driver Code
if __name__ == "__main__":
arr = [[2, 2], [2, 3]]
K = 2
N = 8
print(willAttack(arr, K, N))
# This code is contributed by rakeshsahni
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)
{
// Check if rooks are in same row
// or same column
if ((arr[i, 0] == arr[j, 0])
|| (arr[i, 1] == arr[j, 1]))
ans++;
}
}
}
return ans;
}
// Driver code
public static void Main()
{
int[,] arr = { { 2, 2 }, { 2, 3 } };
int K = 2, N = 8;
Console.WriteLine(willAttack(arr, K, N));
}
}
// This code is contributed by gfgking
Javascript
输出
2
时间复杂度:O(K*K)
辅助空间:O(1)