Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Java Program to Interchange Any Two Rows in the Matrix

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required.

Examples

Input 1: K = 1, L = 2,

          mat[][] = {{2, 1, 4},
                     {1, 2, 3},  
                     {3, 6, 2}}
                     
Output: 
          mat[][] = {{1, 2, 3},
                     {2, 1, 4},  
                     {3, 6, 2}}
                    

Input 2: K = 1, L = 1,
          mat[][] = {{2, 1, 4},
                     {1, 2, 3}} 
                              
Output: 
          mat[][] = {{2, 1, 4},
                     {1, 2, 3}}   
                                   
Input 3: K = 2, L = 3,
          mat[][] =  {{2, 1},
                      {1, 2},  
                      {3, 6}}
                     
Output: 
          mat[][] =  {{2, 1},
                     {3, 6},  
                     {1, 2}}

Approach

  • If First and Second are same, then print the matrix as it is.
  • Else Loop over the Kth and Lth row of the matrix.
  • Swap the elements ith index of both the rows while traversal.
  • Now after the loop gets over, print the matrix.

Below is the code implementation for the above approach:

Java




// Java program to interchange
// two row in a Matrix
import java.io.*;
 
class GFG {
   
    public static void printMatrix(int[][] matrix)
    {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++)
                System.out.print(matrix[i][j] + " ");
            System.out.println();
        }
    }
    public static void exchangeAnyTwoRows(int[][] matrix,
                                          int K, int L)
    {
         
        int[] temp = matrix[K - 1];
        matrix[K - 1]= matrix[L - 1];
        matrix[L - 1] = temp;
       
        // Print matrix
        printMatrix(matrix);
    }
   
    public static void main(String[] args)
    {
        int K = 2, L = 3;
        int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } };
 
        // calling the exchange row function
        exchangeAnyTwoRows(mat, K, L);
    }
}

 
 

Output

2 1 4 
3 6 2 
1 2 3 

 

Time Complexity: 0(n), Where n is the length of the row.

 

Space Complexity: 0(1)

 


My Personal Notes arrow_drop_up
Last Updated : 11 Mar, 2022
Like Article
Save Article
Similar Reads
Related Tutorials