54. Spiral Matrix

54. Spiral Matrix
Medium
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Solution:

    /* startR - starting row index 
       endR - ending row index 
        startC - starting column index 
        endC - ending column index 

class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if(matrix == null) return null; if(matrix.length == 0 || matrix[0].length == 0) return res; int startR = 0; int startC= 0; int endR = matrix.length -1; int endC = matrix[0].length-1;
//test case {{1},{2},{3},{4}} while(startR <= endR && startC <= endC){//both satisfied spiralOneLayer(matrix,res,startR,endR,startC,endC); startR++; endR--; startC++; endC--; } return res; } private void spiralOneLayer(int[][] matrix, List<Integer> res, int startR, int endR, int startC, int endC){ System.out.print(startC+"-"+ endC); if(startR == endR){// when there is one row for(int i = startC; i <= endC; i++){ res.add(matrix[startR][i]); } }else if(startC == endC){// when there is one column for(int i = startR; i <= endR; i++){ res.add(matrix[i][startC]); } }else{ if(startC < endC){ for(int i = startC; i < endC; i++){ res.add(matrix[startR][i]); } } if(startR < endR){ for(int i = startR; i < endR; i++){ res.add(matrix[i][endC]); } } if(startR < endR){ for(int i = endC; i > startC; i--){ res.add(matrix[endR][i]); } } if(startC < endC){ for(int i = endR; i > startR; i--){ res.add(matrix[i][startC]); } } } } }





Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal