Tag Archives: matrix

Print matrix elements in spiral order

This is one of the common interview questions used to test how cleanly you can code without ending up in knots handling the indexes.

Problem statement:

Given an N x M matrix, print the elements in spiral order.
Example for matrix:
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14]
]

Output would be 1 2 3 4 5 10 14 13 12 11 6 7 8 9

Solution:
There could be various ways of solving this. I am sharing the approach I used to solve it.
The idea is to keep 4 indexes to track the matrix boundaries, start with a direction value pointing to right initially and then once it hits the right most boundary, change direction and update the relevant boundary value.
For example, when we are going in right direction, and we hit the boundary, we need to go clockwise and change to go down next and we also need to increment the xMin value as we have covered the row corresponding to that xMin value.

public static void printSpiral(int[][] matrix, int n, int m) {
    int xMin = 0, yMin = 0, xMax = n - 1, yMax = m -1;
    // Current co-ordinates
    int x = 0, y = 0;
    char direction = 'r';
    while (xMin <= xMax && yMin <= yMax) {
        // Get the next direction
        switch(direction) {
        case 'd': if (x == xMax) {direction = 'l'; yMax--;} break;
        case 'r': if (y == yMax) {direction = 'd'; xMin++;} break;
        case 'u': if (x == xMin) {direction = 'r'; yMin++;} break;
        case 'l': if (y == yMin) {direction = 'u'; xMax--;} break;
        }
        // Print the current co-ordinates
        System.out.print(matrix[x][y] + " ");
        // Update the current co-ordinates
        switch(direction) {
        case 'd': x++; break;
        case 'r': y++; break;
        case 'u': x--; break;
        case 'l': y--; break;
        }
    }
}