Queries in a Matrix | Java 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 code ; row [ ] is array for rows and cols [ ] is array for columns ; Fill initial values in rows [ ] and cols [ ]
class GFG { static 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 ; } } static 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 , y - 1 ) ; break ; case ' C ' : swap ( cols , x - 1 , y - 1 ) ; break ; case ' P ' : System . out . printf ( "value at (%d, %d) = %dNEW_LINE", 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 ; } public static void main ( String [ ] args ) { int m = 1234 , n = 5678 ; int rows [ ] = new int [ m ] , cols [ ] = new int [ 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 ) ; } }