Posts Spiral Order Matrix II (InterviewBit)
Post
Cancel

Spiral Order Matrix II (InterviewBit)

PROBLEM DESCRIPTION

Given an integer A, generate a square matrix filled with elements from 1 to A^2 in spiral order and return the generated square matrix.

InterviewBit

SOLUTION

Mark the startRow, endRow, startColumn and endColumn. Then, start iterated over the perimeter in the order: top row -> right column -> bottom row -> left column. Once this is covered, update startRow -> startRow++, endRow -> endRow–, startColumn -> startColumn++ and endColumn -> endColumn– for the next perimeter.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Solution {

    public int[][] generateMatrix(int A) {

        int n = A;

        int[][] matrix = new int[n][n];

        int startRow = 0;
        int endRow = n-1;
        int startColumn = 0;
        int endColumn = n-1;

        int nextVal = 1;

        while(startRow <= endRow && startColumn <= endColumn){

            //top
            for(int i=startColumn; i<=endColumn; i++){
                matrix[startRow][i] = nextVal;
                nextVal++;
            }

            //right
            for(int i=startRow+1; i<=endRow; i++){
                matrix[i][endColumn] = nextVal;
                nextVal++;
            }

            //bottom
            for(int i=endColumn-1; i>=startColumn; i--){
                matrix[endRow][i] = nextVal;
                nextVal++;
            }

            //left
            for(int i=endRow-1; i>=startRow+1; i--){
                matrix[i][startColumn] = nextVal;
                nextVal++;
            }

            startRow++;
            startColumn++;
            endRow--;
            endColumn--;

        }

        return matrix;


    }

}
This post is licensed under CC BY 4.0 by the author.