Spiral Order Matrix I - The Coding Shala

Home >> Interview Questions >> Spiral Order Matrix 1

Spiral Order Matrix I Interview Bit Solution

Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.
Spiral Order Matrix Java Program - The Coding Shala

Example:
Given the following matrix:
[
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
]
You should return
[1, 2, 3, 6, 9, 8, 7, 4, 5]

Solution(Java):

Take four variables top, bottom, left and right. Start printing with the top then right then bottom and then left. Increase the values of variables after printing each row and columns.



 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
public class Solution {
    // DO NOT MODIFY THE LIST. IT IS READ ONLY
    public ArrayList<Integer> spiralOrder(final List<ArrayList<Integer>> A) {
        ArrayList<Integer> ans = new ArrayList<Integer>();
        int t = 0;
        int b = A.size()-1;
        int l = 0;
        int r = A.get(0).size()-1;
       // System.out.println(b+" "+r);
        int dir = 1;
        int tmp = 0;
        while(t<=b && l<=r){
            if(dir == 1){
                for(int i = l; i<= r; i++){
                    ans.add(A.get(t).get(i));
                }
                   // System.out.println(ans.get(tmp)+" "); tmp++;
                    dir = 2;
                    t++;
            }else if(dir == 2){
                for(int i=t;i<=b;i++){
                    ans.add(A.get(i).get(r));}
                   // System.out.println(ans.get(tmp)+" "); tmp++;
                    dir = 3;
                    r--;
                //}
            }else if(dir == 3){
                for(int i=r;i>=l;i--){
                    ans.add(A.get(b).get(i));}
                    //System.out.println(ans.get(tmp)+" "); tmp++;
                    dir = 4;
                    b--;
               // }
            }else if(dir == 4){
                for(int i=b;i>=t;i--){
                    ans.add(A.get(i).get(l));}
                   // System.out.println(ans.get(tmp)+" "); tmp++;
                    dir = 1;
                    l++;
               // }
            }
        }
        return ans;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Program to Convert Decimal to Binary - The Coding Shala