Open In App

Queries in a Matrix

Last Updated : 12 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a matrix M of size m x n ( 1 <= m,n <= 1000 ). It is initially filled with integers from 1 to m x n sequentially in a row major order. The task is to process a list of queries manipulating M such that every query is one of the following three. 

  1. R(x, y): swaps the x-th and y-th rows of M where x and y vary from 1 to m.
  2. C(x, y): swaps the x-th and y-th columns of M where x and y vary from 1 to n.
  3. P(x, y): prints the element at x-th row and y-th column where x varies from 1 to m and y varies from 1 to n.

Note that the given matrix is stored as a typical 2D array with indexes start from 0, but values of x and y start from 1.

Examples: 

Input : m = 3, n = 3
                    R(1, 2)
                    P(1, 1)
                    P(2, 1)
                    C(1, 2)
                    P(1, 1)
                    P(2, 1)
Output: value at (1, 1) = 4
        value at (2, 1) = 1
        value at (1, 1) = 5
        value at (2, 1) = 2
Explanation:
The matrix is {{1, 2, 3}, 
               {4, 5, 6},
               {7, 8, 9}}
After first R(1, 2) matrix becomes, 
              {{4, 5, 6}, 
               {1, 2, 3}, 
               {7, 8, 9}}
After first C(1, 2) matrix becomes, 
              {{5, 4, 6}, 
               {2, 1, 3}, 
               {8, 7, 9}}


Input : m = 1234, n = 5678
                R(1, 2)
                P(1, 1)
                P(2, 1)
                C(1, 2)
                P(1, 1)
                P(2, 1)
Output: value at (1, 1) = 5679
        value at (2, 1) = 1
        value at (1, 1) = 5680
        value at (2, 1) = 2

A simple solution for this problem is to finish all the queries manually, that means when we have to swap the rows just swap the elements of x’th row and y’th row and similarly for column swapping. But this approach may have time complexity of q*O(m) or q*O(n) where ‘q’ is number of queries and auxiliary space required O(m*n).
An efficient approach for this problem requires little bit mathematical observation. Here we are given that elements in matrix are filled from 1 to mxn sequentially in row major order, so we will take advantage of this given scenario and can solve this problem. 

  • Create an auxiliary array rows[m] and fill it with values 0 to m-1 sequentially.
  • Create another auxiliary array cols[n] and fill it with values 0 to n-1 sequentially.
  • Now for query ‘R(x, y)’ just swap the value of rows[x-1] with rows[y-1].
  • Now for query ‘C(x, y)’ just swap the value of cols[x-1] with cols[y-1].
  • Now for query ‘P(x, y)’ just skip the number of columns you have seen and calculate the value at (x, y) by rows[x-1]*n + cols[y-1] + 1.

Below is implementation of above idea. 

C++




// C++ implementation of program
#include<bits/stdc++.h>
using namespace std;
 
// Fills initial values in rows[] and cols[]
void preprocessMatrix(int rows[], int cols[],
                     int m, int n)
{
    // Fill rows with 1 to m-1
    for (int i=0; i<m; i++)
        rows[i] = i;
 
    // Fill columns with 1 to n-1
    for (int i=0; i<n; i++)
        cols[i] = i;
}
 
// Function to perform queries on matrix
// m --> number of rows
// n --> number of columns
// ch --> type of query
// x --> number of row for query
// y --> number of column for query
void queryMatrix(int rows[], int cols[], int m,
                 int n, char ch, int x, int y)
{
    // perform queries
    int tmp;
    switch(ch)
    {
    case 'R':
 
        // swap row x with y
        swap(rows[x-1], rows[y-1]);
        break;
 
    case 'C':
 
        // swap column x with y
        swap(cols[x-1], cols[y-1]);
        break;
 
    case 'P':
 
        // Print value at (x, y)
        printf("value at (%d, %d) = %d\n", x, y,
                   rows[x-1]*n + cols[y-1]+1);
        break;
    }
    return ;
}
 
// Driver program to run the case
int main()
{
    int m = 1234, n = 5678;
 
    // row[] is array for rows and cols[]
    // is array for columns
    int rows[m], cols[n];
 
    // Fill initial values in rows[] and cols[]
    preprocessMatrix(rows, cols, m, n);
 
    queryMatrix(rows, cols, m, n, 'R', 1, 2);
    queryMatrix(rows, cols, m, n, 'P', 1, 1);
    queryMatrix(rows, cols, m, n, 'P', 2, 1);
    queryMatrix(rows, cols, m, n, 'C', 1, 2);
    queryMatrix(rows, cols, m, n, 'P', 1, 1);
    queryMatrix(rows, cols, m, n, 'P', 2, 1);
    return 0;
}


Java




// Java implementation of program
import java.io.*;
class GFG
{
 
    // Fills initial values in rows[] and cols[]
    static void preprocessMatrix(int rows[], int cols[],
                                        int m, int n)
    {
        // Fill rows with 1 to m-1
        for (int i = 0; i < m; i++)
        {
            rows[i] = i;
        }
 
        // Fill columns with 1 to n-1
        for (int i = 0; i < n; i++)
        {
            cols[i] = i;
        }
    }
 
    // Function to perform queries on matrix
    // m --> number of rows
    // n --> number of columns
    // ch --> type of query
    // x --> number of row for query
    // y --> number of column for query
    static void queryMatrix(int rows[], int cols[], int m,
                            int n, char ch, int x, int y)
    {
        // perform queries
        int tmp;
        switch (ch)
        {
            case 'R':
 
                // swap row x with y
                swap(rows, x - 1, y - 1);
                break;
 
            case 'C':
 
                // swap column x with y
                swap(cols, x - 1, y - 1);
                break;
 
            case 'P':
 
                // Print value at (x, y)
                System.out.printf("value at (%d, %d) = %d\n", x, y,
                        rows[x - 1] * n + cols[y - 1] + 1);
                break;
        }
        return;
    }
 
    static int[] swap(int[] arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return arr;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int m = 1234, n = 5678;
 
        // row[] is array for rows and cols[]
        // is array for columns
        int rows[] = new int[m], cols[] = new int[n];
 
        // Fill initial values in rows[] and cols[]
        preprocessMatrix(rows, cols, m, n);
 
        queryMatrix(rows, cols, m, n, 'R', 1, 2);
        queryMatrix(rows, cols, m, n, 'P', 1, 1);
        queryMatrix(rows, cols, m, n, 'P', 2, 1);
        queryMatrix(rows, cols, m, n, 'C', 1, 2);
        queryMatrix(rows, cols, m, n, 'P', 1, 1);
        queryMatrix(rows, cols, m, n, 'P', 2, 1);
    }
}
 
// This code contributed by Rajput-Ji


Python3




# Python3 implementation of program
 
# Fills initial values in rows[] and cols[]
def preprocessMatrix(rows, cols, m, n):
 
    # Fill rows with 1 to m-1
    for i in range(m):
        rows[i] = i;
 
    # Fill columns with 1 to n-1
    for i in range(n):
        cols[i] = i;
 
# Function to perform queries on matrix
# m --> number of rows
# n --> number of columns
# ch --> type of query
# x --> number of row for query
# y --> number of column for query
def queryMatrix(rows, cols, m, n, ch, x, y):
 
    # perform queries
    tmp = 0;
     
    if ch == 'R':
 
        # swap row x with y
        rows[x-1], rows[y-1] = rows[y-1], rows[x-1];
 
    elif ch == 'C':
 
        # swap column x with y
        cols[x-1], cols[y-1] = cols[y-1],cols[x-1];
 
    elif ch == 'P':
 
        # Print value at (x, y)
        print('value at (',x,',',y,') = ',rows[x-1]*n + cols[y-1]+1, sep='');
         
    return ;
 
# Driver program to run the case
m = 1234
n = 5678;
 
# row[] is array for rows and cols[]
# is array for columns
rows = [0 for i in range(m)]
cols = [0 for i in range(n)];
 
# Fill initial values in rows[] and cols[]
preprocessMatrix(rows, cols, m, n);
 
queryMatrix(rows, cols, m, n, 'R', 1, 2);
queryMatrix(rows, cols, m, n, 'P', 1, 1);
queryMatrix(rows, cols, m, n, 'P', 2, 1);
queryMatrix(rows, cols, m, n, 'C', 1, 2);
queryMatrix(rows, cols, m, n, 'P', 1, 1);
queryMatrix(rows, cols, m, n, 'P', 2, 1);
 
# This code is contributed by rutvik_56.


C#




// C# implementation of program
using System;
 
class GFG
{
 
    // Fills initial values in rows[] and cols[]
    static void preprocessMatrix(int []rows, int []cols,
                                        int m, int n)
    {
        // Fill rows with 1 to m-1
        for (int i = 0; i < m; i++)
        {
            rows[i] = i;
        }
 
        // Fill columns with 1 to n-1
        for (int i = 0; i < n; i++)
        {
            cols[i] = i;
        }
    }
 
    // Function to perform queries on matrix
    // m --> number of rows
    // n --> number of columns
    // ch --> type of query
    // x --> number of row for query
    // y --> number of column for query
    static void queryMatrix(int []rows, int []cols, int m,
                            int n, char ch, int x, int y)
    {
        // perform queries
        int tmp;
        switch (ch)
        {
            case 'R':
 
                // swap row x with y
                swap(rows, x - 1, y - 1);
                break;
 
            case 'C':
 
                // swap column x with y
                swap(cols, x - 1, y - 1);
                break;
 
            case 'P':
 
                // Print value at (x, y)
                Console.Write("value at ({0}, {1}) = {2}\n", x, y,
                        rows[x - 1] * n + cols[y - 1] + 1);
                break;
        }
        return;
    }
 
    static int[] swap(int[] arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return arr;
    }
 
    // Driver code
    public static void Main()
    {
        int m = 1234, n = 5678;
 
        // row[] is array for rows and cols[]
        // is array for columns
        int []rows = new int[m]; int []cols = new int[n];
 
        // Fill initial values in rows[] and cols[]
        preprocessMatrix(rows, cols, m, n);
 
        queryMatrix(rows, cols, m, n, 'R', 1, 2);
        queryMatrix(rows, cols, m, n, 'P', 1, 1);
        queryMatrix(rows, cols, m, n, 'P', 2, 1);
        queryMatrix(rows, cols, m, n, 'C', 1, 2);
        queryMatrix(rows, cols, m, n, 'P', 1, 1);
        queryMatrix(rows, cols, m, n, 'P', 2, 1);
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
 
// JavaScript implementation of program
// Fills initial values in rows[] and cols[]
function preprocessMatrix(rows, cols, m, n)
{
    // Fill rows with 1 to m-1
    for (var i = 0; i < m; i++)
    {
        rows[i] = i;
    }
    // Fill columns with 1 to n-1
    for (var i = 0; i < n; i++)
    {
        cols[i] = i;
    }
}
// Function to perform queries on matrix
// m --> number of rows
// n --> number of columns
// ch --> type of query
// x --> number of row for query
// y --> number of column for query
function queryMatrix(rows, cols, m, n, ch, x, y)
{
    // perform queries
    var tmp;
    switch (ch)
    {
        case 'R':
            // swap row x with y
            swap(rows, x - 1, y - 1);
            break;
        case 'C':
            // swap column x with y
            swap(cols, x - 1, y - 1);
            break;
        case 'P':
            // Print value at (x, y)
            document.write(`value at
            (${x}, ${y}) = ${rows[x - 1] * n + cols[y - 1] + 1}<br>`);
            break;
    }
    return;
}
function swap(arr, i, j)
{
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
}
// Driver code
var m = 1234, n = 5678;
// row[] is array for rows and cols[]
// is array for columns
var rows = Array(m).fill(0)
var cols = Array(n).fill(0)
// Fill initial values in rows[] and cols[]
preprocessMatrix(rows, cols, m, n);
queryMatrix(rows, cols, m, n, 'R', 1, 2);
queryMatrix(rows, cols, m, n, 'P', 1, 1);
queryMatrix(rows, cols, m, n, 'P', 2, 1);
queryMatrix(rows, cols, m, n, 'C', 1, 2);
queryMatrix(rows, cols, m, n, 'P', 1, 1);
queryMatrix(rows, cols, m, n, 'P', 2, 1);
 
 
</script>


Output

value at (1, 1) = 5679
value at (2, 1) = 1
value at (1, 1) = 5680
value at (2, 1) = 2

Time Complexity : O(q) , q = number of queries 
Axillary Space : O(m+n)

 



Previous Article
Next Article

Similar Reads

Array range queries over range queries
Given an array of size n and a give set of commands of size m. The commands are enumerated from 1 to m. These commands can be of the following two types of commands: Type 1 [l r (1 &lt;= l &lt;= r &lt;= n)] : Increase all elements of the array by one, whose indices belongs to the range [l, r]. In these queries of the index is inclusive in the range
41 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
19 min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Queries for bitwise AND in the given matrix
Given an N * N matrix mat[][] consisting of non-negative integers and some queries consisting of top-left and bottom-right corner of the sub-matrix, the task is to find the bit-wise AND of all the elements of the sub-matrix given in each query. Examples: Input: mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, q[] = {{1, 1, 1, 1}, {1, 2, 2, 2}} Output:
11 min read
Queries for bitwise OR in the given matrix
Given an N * N matrix mat[][] consisting of non-negative integers and some queries consisting of top-left and bottom-right corner of the sub-matrix, the task is to find the bit-wise OR of all the elements of the sub-matrix given in each query.Examples: Input: mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, q[] = {{1, 1, 1, 1}, {1, 2, 2, 2}} Output: 5
11 min read
Find Number of Even cells in a Zero Matrix after Q queries
Given a Zero matrix of N x N size, the task is to find the numbers of cells containing even numbers after performing Q queries. Each query will be in the form of (X, Y) such that for a given cell (X, Y), an increment operation has to be performed on all cells in the X'th row and Y'th column.Note: The initial 0's are also to be taken as even numbers
9 min read
Queries to find the count of connected Non-Empty Cells in a Matrix with updates
Given a boolean matrix mat[][] consisting of N rows and M columns, initially filled with 0's(empty cells), an integer K and queries Q[][] of the type {X, Y}, the task is to replace mat[X][Y] = 1(non-empty cells) and count the number of connected non-empty cells from the given matrix.Examples: Input: N = 3, M = 3, K = 4, Q[][] = {{0, 0}, {1, 1}, {1,
16 min read
Final Matrix after incrementing submatrices by K in range given by Q queries
Given a 2D matrix mat[][] of size N*M and Q queries of the form {x1, y1, x2, y2, K}. For each query, the task is to add the value K to submatrix from cell (x1, y1) to (x2, y2). Print the matrix after all the queries performed. Examples: Input: N = 3, M = 4, mat[][] = {{1, 0, 1, 2}, {0, 2, 4, 1}, {1, 2, 1, 0}}, Q = 1, Queries[][] = {{0, 0, 1, 1, 2}}
14 min read
Binary Matrix after flipping submatrices in given range for Q queries
Given a binary matrix arr[][] of dimensions M x N and Q queries of the form (x1, y1, x2, y2), where (x1, y1) and (x2, y2) denotes the top-left and bottom-right indices of the submatrix required to be flipped(convert 0s to 1s and vice versa) respectively. The task is to print the final matrix obtained after performing the given Q queries. Examples:
15 min read
Queries to check if a path made up of even numbers from source to destination exists in a Matrix
Given two arrays R[] and C[] consisting of N integers such that a matrix of dimensions N x N can be formed whose element at index (i, j) is given by (R[i] + C[j]) for all possible pairs from the two arrays. Given a matrix Queries[][] with each row representing a query of the type {A, B, X, Y}, the task for each query is to check whether there exist
13 min read
Article Tags :
Practice Tags :