27 Apr 2014

Matrix: Spiral Printing

Problem Statement:
          Print the given matrix (m X n) in spiral form.

Fig: Matrix: print elements spirally

Solution:
  Run Source Code

This question was asked to my buddy in Tower Research Capital.
This problem is not difficult but, you will be tested if you can get the output in one go.
We would require 5 loops, out of which 4 loops will be for printing the elements in
LEFT, DOWN, RIGHT and UP. Below i have given the implementation of the problem.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
  * Spiral order printing
  * @param matrix
  */
 public static void printSpiral(int[][] matrix) {
  int rowSize = matrix.length;
  int colSize = matrix[0].length;

  int row = 0, col = 0, i;

  while (row < rowSize && col < colSize) {
   i = col;
   for (; i < colSize - col; i++)
    System.out.print(matrix[row][i] + "  ");

   i = row + 1;
   for (; i < rowSize - row; i++)
    System.out.print(matrix[i][colSize - col - 1] + "  ");

   i = (colSize - 1 - col) - 1;
   for (; i >= col; i--)
    System.out.print(matrix[rowSize - row - 1][i] + "  ");

   i = (rowSize - 1 - row) - 1;
   for (; i > row; i--)
    System.out.print(matrix[i][col] + "  ");

   row++;
   col++;
  }
 }

Download Source Code
Please comment and post your suggestions.
Happy Coding !! :)

1 comment: