Maximum non-attacking Rooks that can be placed on an N*N Chessboard

07 Mar, 2022
Given an integers N such that there is a chessboard of size N*N and an array pos[][] of K pairs of integers which represent the positions of placed rooked in the given chessboard. The task is to find the maximum number of rooks with their positions that can be placed on the given chessboard such that no rook attacks some other rook. Print the positions in lexicographical order.
Examples:
Input: N = 4, K = 2, pos[][] = {{1, 4}, {2, 2}} Output: 2 3 1 4 3 Explanation: Only 2 more rooks can be placed on the given chessboard and their positions are (3, 1) and (4, 3).Input: N = 5, K = 0, pos[][] = {} Output: 5 1 1 2 2 3 3 4 4 5 5 Explanation: Since the chessboard is empty we can place 5 rooks the given chessboard and their positions are (1, 1), (2, 2), (3, 3), (4, 4) and (5, 5).
Naive Approach: The simplest approach is to try to place a rook at every empty position of the chessboard and check if it attacks the already placed rooks or not. Below are the steps:
Initialize a 2D matrix M[][] of size N*N to represent the chessboard and place the already given rooks in it.Transverse the complete matrix M[][] and check if the ith row and jth column contains any rookIf the ith row and jth column both don’t contain any rook, then a rook is placed there and this cell is added to the result.Otherwise, move to the next empty cell on the chessboard.
Initialize a 2D matrix M[][] of size N*N to represent the chessboard and place the already given rooks in it.
Transverse the complete matrix M[][] and check if the ith row and jth column contains any rook
If the ith row and jth column both don’t contain any rook, then a rook is placed there and this cell is added to the result.
Otherwise, move to the next empty cell on the chessboard.
Time Complexity: O(N3) Auxiliary Space: O(N2)
Efficient Approach: The approach is based on the idea that a maximum of (N – K) rooks can be placed on the chessboard according to the Pigeonhole Principle. Below are the steps:
Since no two of the given rooks attack each other, all the rows given in the input must be unique. Similarly, all the columns given in the input must be unique.So, place the rooks only in N – K unused rows and N – K unused columns.Therefore, lexicographically minimum configuration can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column, and so on.
Since no two of the given rooks attack each other, all the rows given in the input must be unique. Similarly, all the columns given in the input must be unique.
So, place the rooks only in N – K unused rows and N – K unused columns.
Therefore, lexicographically minimum configuration can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column, and so on.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the maximum rooks// and their positionsvoid countRooks(int n, int k,                int pos[2][2]) {     int row[n] = {0};     int col[n] = {0};      // Initialize row and col array     for (int i = 0; i < n; i++)     {         row[i] = 0;         col[i] = 0;     }      // Marking the location of     // already placed rooks     for (int i = 0; i < k; i++)     {         row[pos[i][0] - 1] = 1;         col[pos[i][1] - 1] = 1;     }      int res = n - k;      // Print number of non-attacking     // rooks that can be placed     cout << res << " " << endl;      // To store the placed rook     // location     int ri = 0, ci = 0;     while (res-- > 0)     {         // Print lexicographically         // smallest order         while (row[ri] == 1)         {             ri++;         }         while (col[ci] == 1)         {             ci++;         }         cout << (ri + 1) << " " <<                 (ci + 1) << " " <<endl;         ri++;         ci++;     } } // Driver Codeint main(){ // Size of board    int N = 4;     // Number of rooks already placed    int K = 2;     // Position of rooks    int pos[2][2] = {{1, 4}, {2, 2}};     // Function call    countRooks(N, K, pos);}// This code is contributed by shikhasingrajput
// Java program for the above approachpublic class GFG {     // Function to print the maximum rooks    // and their positions    private static void countRooks(int n, int k,                                   int pos[][])    {        int row[] = new int[n];        int col[] = new int[n];         // Initialize row and col array        for (int i = 0; i < n; i++) {            row[i] = 0;            col[i] = 0;        }         // Marking the location of        // already placed rooks        for (int i = 0; i < k; i++) {            row[pos[i][0] - 1] = 1;            col[pos[i][1] - 1] = 1;        }         int res = n - k;         // Print number of non-attacking        // rooks that can be placed        System.out.println(res + " ");         // To store the placed rook        // location        int ri = 0, ci = 0;        while (res-- > 0) {             // Print lexicographically            // smallest order            while (row[ri] == 1) {                ri++;            }            while (col[ci] == 1) {                ci++;            }            System.out.println(                (ri + 1)                + " " + (ci + 1)                + " ");            ri++;            ci++;        }    }     // Driver Code    public static void main(String[] args)    {         // Size of board        int N = 4;         // Number of rooks already placed        int K = 2;         // Position of rooks        int pos[][] = { { 1, 4 }, { 2, 2 } };         // Function call        countRooks(N, K, pos);    }}
# Python3 program for the above approach# Function to print maximum rooks# and their positionsdef countRooks(n, k, pos):         row = [0 for i in range(n)]    col = [0 for i in range(n)]     # Marking the location of    # already placed rooks    for i in range(k):        row[pos[i][0] - 1] = 1        col[pos[i][1] - 1] = 1     res = n - k     # Print number of non-attacking    # rooks that can be placed    print(res)     # To store the placed rook    # location    ri = 0    ci = 0         while (res > 0):         # Print lexicographically        # smallest order        while (row[ri] == 1):            ri += 1                     while (col[ci] == 1):            ci += 1                     print((ri + 1), (ci + 1))                 ri += 1        ci += 1        res -= 1 # Driver Codeif __name__ == '__main__':     # Size of board    N = 4     # Number of rooks already placed    K = 2     # Position of rooks    pos= [ [ 1, 4 ], [ 2, 2 ] ]     # Function call    countRooks(N, K, pos) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;class GFG{     // Function to print the maximum rooks    // and their positions    private static void countRooks(int n, int k,                                   int [, ]pos)    {        int []row = new int[n];        int []col = new int[n];         // Initialize row and col array        for (int i = 0; i < n; i++)        {            row[i] = 0;            col[i] = 0;        }         // Marking the location of        // already placed rooks        for (int i = 0; i < k; i++)        {            row[pos[i, 0] - 1] = 1;            col[pos[i, 1] - 1] = 1;        }         int res = n - k;         // Print number of non-attacking        // rooks that can be placed        Console.WriteLine(res + " ");         // To store the placed rook        // location        int ri = 0, ci = 0;        while (res -- > 0)        {            // Print lexicographically            // smallest order            while (row[ri] == 1)            {                ri++;            }            while (col[ci] == 1)            {                ci++;            }            Console.WriteLine((ri + 1) + " " +                              (ci + 1) + " ");            ri++;            ci++;        }    }     // Driver Code    public static void Main(String[] args)    {        // Size of board        int N = 4;         // Number of rooks already placed        int K = 2;         // Position of rooks        int [, ]pos = {{1, 4}, {2, 2}};         // Function call        countRooks(N, K, pos);    }} // This code is contributed by Rajput-Ji
<script> // Javascript program to implement// the above approach     // Function to print the maximum rooks    // and their positions    function countRooks(n, k, pos)    {        let row = new Array(n).fill(0);        let col = new Array(n).fill(0);          // Initialize row and col array        for (let i = 0; i < n; i++) {            row[i] = 0;            col[i] = 0;        }          // Marking the location of        // already placed rooks        for (let i = 0; i < k; i++) {            row[pos[i][0] - 1] = 1;            col[pos[i][1] - 1] = 1;        }          let res = n - k;          // Print number of non-attacking        // rooks that can be placed        document.write(res + " " + "<br/>");          // To store the placed rook        // location        let ri = 0, ci = 0;        while (res-- > 0) {              // Print lexicographically            // smallest order            while (row[ri] == 1) {                ri++;            }            while (col[ci] == 1) {                ci++;            }            document.write(                (ri + 1)                + " " + (ci + 1)                + " " + "<br/>");            ri++;            ci++;        }    } // Driver Code              // Size of board        let N = 4;          // Number of rooks already placed        let K = 2;          // Position of rooks        let pos = [[ 1, 4 ], [ 2, 2 ]];          // Function call        countRooks(N, K, pos);                 </script>
2 
3 1 
4 3
Time Complexity: O(N2) Auxiliary Space: O(N2) 
mohit kumar 29
Rajput-Ji
shikhasingrajput
avijitmondal1998
khushboogoyal499
ankita_saini
simranarora5sos
chessboard-problems
Mathematical
Matrix
Searching
Searching
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Matrix Chain Multiplication | DP-8
Print a given matrix in spiral form
Program to find largest element in an array
Sudoku | Backtracking-7
The Celebrity Problem