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