Created
February 13, 2018 23:22
-
-
Save jianminchen/c9a9d09f4631e485286be417c201ab45 to your computer and use it in GitHub Desktop.
Leetcode 54 Spiral matrix - Study java code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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