Posts Spirally traversing a matrix (geeksforgeeks - SDE Sheet)
Post
Cancel

Spirally traversing a matrix (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

You are given a rectangular matrix, and your task is to return an array while traversing the matrix in spiral form.

geeksforgeeks

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

    // Function to return a list of integers denoting spiral traversal of matrix.
    public ArrayList<Integer> spirallyTraverse(int matrix[][]) {

        int n = matrix.length;
        int m = matrix[0].length;

        int topRow = 0;
        int bottomRow = n-1;

        int leftColumn = 0;
        int rightColumn = m-1;

        ArrayList<Integer> list = new ArrayList<>();

        while(topRow <= bottomRow && leftColumn <= rightColumn){

            // top
            for(int c=leftColumn; c<=rightColumn; c++){
                list.add(matrix[topRow][c]);
            }

            // right
            for(int r=topRow+1; r<=bottomRow; r++){
                list.add(matrix[r][rightColumn]);
            }

            // bottom
            for(int c=rightColumn-1; c>=leftColumn; c--){
                if(topRow == bottomRow) break;
                list.add(matrix[bottomRow][c]);
            }

            // left
            for(int r=bottomRow-1; r>=topRow+1; r--){
                if(leftColumn == rightColumn) break;
                list.add(matrix[r][leftColumn]);
            }

            topRow++;
            bottomRow--;
            leftColumn++;
            rightColumn--;

        }

        return list;

    }

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