Spiral Traversal of Matrix

#include <iostream>
using namespace std;

int mat[4][3] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};

void print_spiral(int mat[4][3], int m, int n, int k) {
  if (m <= 0 || n <= 0)
    return;
  if (m == 1) {
    for (int j = 0; j < n; j++)
      cout << mat[k][k+j] << " ";
    return;
  }
  if (n == 1) {
    for (int i = 0; i < m; i++)
      cout << mat[k+i][k] << " ";
    return;
  }
  // print from top left
  for (int j = 0; j < n - 1; j++)
    cout << mat[k][k+j] << " ";
  // print from top right
  for (int i = 0; i < m - 1; i++)
    cout << mat[k+i][k+n-1] << " ";
  // print from bottom right
  for (int j = 0; j < n - 1; j++)
    cout << mat[k+m-1][k+n-1-j] << " ";
  // print from bottom left
  for (int i = 0; i < m - 1; i++)
    cout << mat[k+m-1-i][k] << " ";

  print_spiral(mat, m-2, n-2, k+1);
}

int main()
{
    int m = 4;
    int n = 3;

    print_spiral(mat, m, n, 0);
    return 0;
}

Comments

Popular posts from this blog

Get current executing method name in Java

Java toString()

Little Endian and Big Endian