Spirally traversing a matrix of matrix in java

Spirally traversing a matrix in java

Given a matrix of size r*c. Traverse the matrix in spiral form.

Expected Time Complexity: O(rxc)
Expected Auxiliary Space: O(rxc), for returning the answer only.

Input

  • The first line contains two integers r and c.
  • The next r lines contains c spaced integers , elements of matrix.

Constraints

  • 1 <= r, c <= 100
  • 0 <= matrix[i][j] <= 100

Output

Print the spiral matrix.

Example

Sample Input

4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Sample Output

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Explanation

 Sample Input

3 4  
1 2 3 4
5 6 7 8
9 10 11 12

Sample Output

1 2 3 4 8 12 11 10 9 5 6 7

Explanation

Applying same technique as shown above, 
output for the 2nd testcase will be 
1 2 3 4 8 12 11 10 9 5 6 7.

Solution of Spirally traversing a matrix :–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int r = sc.nextInt();
      int c = sc.nextInt();

      int mat[][] = new int[r][c];

      for(int i=0;i<mat.length;i++)
        {
          for(int j=0;j<mat[i].length;j++)
            {
              mat[i][j]=sc.nextInt();
            }
        }

          // base case
		if (mat == null || mat.length == 0) {
			return;
		}

		int top = 0, bottom = mat.length - 1;
		int left = 0, right = mat[0].length - 1;

		while (true)
		{
			if (left > right) {
				break;
			}

			// print top row
			for (int i = left; i <= right; i++) {
				System.out.print(mat[top][i] + " ");
			}
			top++;

			if (top > bottom) {
				break;
			}

			// print right column
			for (int i = top; i <= bottom; i++) {
				System.out.print(mat[i][right] + " ");
			}
			right--;

			if (left > right) {
				break;
			}

			// print bottom row
			for (int i = right; i >= left; i--) {
				System.out.print(mat[bottom][i] + " ");
			}
			bottom--;

			if (top > bottom) {
				break;
			}

			// print left column
			for (int i = bottom; i >= top; i--) {
				System.out.print(mat[i][left] + " ");
			}
			left++;
		
      
        
        }
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *