Find position of non-attacking Rooks in lexicographic order that can be placed on N*N chessboard - GeeksforGeeks

07 Mar, 2022
Given an integer N and an array arr[] of positions which denotes the positions of already placed non-attacking rooks, the task is to find the positions of non-attacking rooks in lexicographic order that can be placed on N*N chessboard.Movement of Rooks: Any rook can move horizontally or vertically by any number of unoccupied squares.
Examples: 
Input: N = 4, arr[] = {(1, 4), (2, 2)}Output: 23 14 3Explanation:There can be two more rooks can be placed on the 4*4 Chessboard 
Input: N = 5, arr[] = {}Output: 51 12 23 34 45 5
Naive Approach: Initialize a 2D Matrix mat[][] of size N*N with 0 at every cell and mark as rooks for initially positions of Rooks by 1.  Then traverse through matrix mat[][], checking whether ith row and jth column contains any rook,  Keeping a count of rooks placed. If any row contains and column both doesn’t contains any placed rook, then place a rook there and add this cell to your result String. Finally, print count of rooks placed and positions of the rooks placementTime Complexity: O(N3) Space Complexity: O(N2) Efficient Approach: The idea is to create two arrays of N size each, to store whether ith row or ith column contains any rook or not and it will now become efficient to search whether this row and the corresponding column already contains Rook or not. Time Complexity: O(N2) Space Complexity: O(N)  
Most Efficient Approach:  The key observation in the problem is that the maximum rook that can be placed is N-K.  That is, Two rooks attack each other if they’re on the same row or on the same column. Since no two of the given rooks attack each other, all of the rows given in the input are unique. Similarly, all of the columns given in the input are unique. So, we’re left with N-K unused rows and N-K unused columns to put the new rooks on. In other words, if we try to put more than N-K rooks by Pigeonhole Principle, if there are N+1 pigeons and N places to fill, then at least one place contains more than 1 pigeon.And to find the lexicographically minimum answer. This answer 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. Time Complexity: O(N)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find// count of placing non-attacking// rooks on the N x N chessboard#include <bits/stdc++.h>using namespace std; // Function to find the count of// placing non-attacking rooks// on the N x N chessboardvoid findCountRooks(int row[], int col[],                    int n, int k){         // Count of the Non-attacking rooks    int res = n - k;    cout << res << "\n";         int ri = 0, ci = 0;         while (res-- > 0)    {                 // Printing lexicographically        // smallest configuration        while (ri < k && row[ri] == 1)        {            ri++;        }        while (ci < k && col[ci] == 1)        {            ci++;        }        cout << (ri + 1) << " "             << (ci + 1) << "\n";                  ri++;        ci++;    }} // Driver Codeint main(){    int n = 4;    int k = 2;    int row[] = { 1, 2 };    int col[] = { 4, 2 };     // Function call    findCountRooks(row, col, n, k);    return 0;} // This code is contributed by jana_sayantan
// Java implementation to find// count of placing non-attacking// rooks on the N x N chessboard import java.util.Scanner; public class P2Placerooks {    // Function to find the count of    // placing non-attacking rooks    // on the N x N chessboard    static void findCountRooks(        int row[], int col[], int n, int k)    {         // Count of the Non-attacking rooks        int res = n - k;        System.out.println(res + " ");        int ri = 0, ci = 0;        while (res-- > 0) {             // Printing lexicographically            // smallest configuration            while (ri < k && row[ri] == 1) {                ri++;            }            while (ci < k && col[ci] == 1) {                ci++;            }            System.out.println((ri + 1)                               + " " + (ci + 1)                               + " ");            ri++;            ci++;        }    }     // Driver Code    public static void main(String[] args)    {        int n = 4;        int k = 2;        int row[] = { 1, 2 };        int col[] = { 4, 2 };         // Function Call        findCountRooks(row, col, n, k);    }}
# Python3 implementation to find# count of placing non-attacking# rooks on the N x N chessboard # Function to find the count of# placing non-attacking rooks# on the N x N chessboarddef findCountRooks(row, col, n, k):         # Count of the Non-attacking rooks    res = n - k    print(res)         ri = 0    ci = 0         while (res > 0):                 # Printing lexicographically        # smallest configuration        while (ri < k and row[ri] == 1):            ri += 1                 while (ci < k and col[ci] == 1):            ci += 1                 print((ri + 1), "", (ci + 1))                 ri += 1        ci += 1        res -= 1     # Driver Coden = 4k = 2 row = [ 1, 2 ]col = [ 4, 2 ] # Function callfindCountRooks(row, col, n, k) # This code is contributed by sanjoy_62
// C# implementation to find// count of placing non-attacking// rooks on the N x N chessboardusing System; class P2Placerooks{     // Function to find the count of// placing non-attacking rooks// on the N x N chessboardstatic void findCountRooks(int []row,                           int []col,                           int n, int k){         // Count of the Non-attacking rooks    int res = n - k;    Console.WriteLine(res + " ");         int ri = 0, ci = 0;    while (res-- > 0)    {                 // Printing lexicographically        // smallest configuration        while (ri < k && row[ri] == 1)        {            ri++;        }        while (ci < k && col[ci] == 1)        {            ci++;        }        Console.WriteLine((ri + 1) + " " +                          (ci + 1) + " ");        ri++;        ci++;    }} // Driver Codepublic static void Main(String[] args){    int n = 4;    int k = 2;    int []row = { 1, 2 };    int []col = { 4, 2 };     // Function call    findCountRooks(row, col, n, k);}} // This code is contributed by Rajput-Ji
<script> // JavaScript implementation to find// count of placing non-attacking// rooks on the N x N chessboard  // Function to find the count of// placing non-attacking rooks// on the N x N chessboardfunction findCountRooks(row,col,n,k){         // Count of the Non-attacking rooks    let res = n - k;    document.write(res + "<br>");         let ri = 0, ci = 0;         while (res-- > 0)    {                 // Printing lexicographically        // smallest configuration        while (ri < k && row[ri] == 1)        {            ri++;        }        while (ci < k && col[ci] == 1)        {            ci++;        }        document.write((ri + 1) + " "            + (ci + 1) + "<br>");                 ri++;        ci++;    }} // Driver Code     let n = 4;    let k = 2;    let row = [ 1, 2 ];    let col = [ 4, 2 ];     // Function call    findCountRooks(row, col, n, k);     </script>
2 
2 1 
3 2
Performance Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
Rajput-Ji
jana_sayantan
sanjoy_62
vaibhavrabadiya117
kalrap615
simranarora5sos
chessboard-problems
lexicographic-ordering
Analysis
Arrays
Data Structures
Matrix
Data Structures
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Time Complexity of building a heap
Analysis of Algorithms | Big-O analysis
Difference between NP hard and NP complete problem
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation