Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created February 13, 2018 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/c9a9d09f4631e485286be417c201ab45 to your computer and use it in GitHub Desktop.
Save jianminchen/c9a9d09f4631e485286be417c201ab45 to your computer and use it in GitHub Desktop.
Leetcode 54 Spiral matrix - Study java code
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
if(matrix==null || matrix.length==0 || matrix[0].length==0) return new ArrayList<Integer>();
return spiralOrder(matrix,0,0,matrix.length,matrix[0].length);
}
// June 11, 2015 Julia likes the implementation documented in the blog.
// She chose to study the algorithm. At that time, she did not know that
// Leetcode has discussion panel, and there are hundreds of ideas in the
// discussion panel
// this one is recursive solution, base cases are clearly presented
// at the beginning of the function
//http://gongxuns.blogspot.ca/2012/12/leetcode-spiral-matrix.html
public ArrayList<Integer> spiralOrder(int [][] matrix, int x, int y, int m, int n){
ArrayList<Integer> res = new ArrayList<Integer>();
// base cases:
if(m <= 0|| n <= 0) return res;
// one element
if(m ==1 && n == 1) {
res.add(matrix[x][y]);
return res;
}
// one row
for(int i=0;i<n-1;i++){
res.add(matrix[x][y++]);
}
// one column
for(int i=0;i<m-1;i++){
res.add(matrix[x++][y]);
}
if( m>1 ){
for(int i=0;i<n-1;i++){
res.add(matrix[x][y--]);
}
}
if(n>1){
for(int i=0;i<m-1;i++){
res.add(matrix[x--][y]);
}
}
if( m==1 || n==1)
res.addAll(spiralOrder(matrix,x,y,1,1));
else
res.addAll(spiralOrder(matrix,x+1,y+1,m-2,n-2));
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment