Saturday, January 30, 2016

Print matrix in Spiral Order

Print matrix in Spiral Order


Problem:
Given a matrix of m x n elements (m rows, n columns), write a function that prints the elements in the matrix in a spiral manner.
Solution:
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
void spiralOrder(int a[][], int m, int n, int k) {
  if (m <= 0 || n <= 0)
    return;
  if (m == 1) {
    for (int j = 0; j < n; j++)
      system.out.print(a[k][k+j] + " ");
    return;
  }
  if (n == 1) {
    for (int i = 0; i < m; i++)
      system.out.print(a[k+i][k] + " ");
    return;
  }
  // print from top left
  for (int j = 0; j < n - 1; j++)
    system.out.print(a[k][k+j] + " ");
  // print from top right
  for (int i = 0; i < m - 1; i++)
    system.out.print(a[k+i][k+n-1] + " ");
  // print from bottom right
  for (int j = 0; j < n - 1; j++)
    system.out.print(a[k+m-1][k+n-1-j] + " ");
  // print from bottom left
  for (int i = 0; i < m - 1; i++)
    system.out.print(a[k+m-1-i][k] + " ");
  
  print_spiral(a, m-2, n-2, k+1);
}

No comments:

Post a Comment