2ms Java recursive solution


  • 0
    Z

    The idea is direct. Add each outside circle of matrix step by step. Be care to stop the recursion when it reaches the end.

    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
        	List<Integer> res = new ArrayList<Integer>();
        	helper(matrix, 0, res);
        	return res;
        }
        public void helper(int[][] matrix, int k, List<Integer> res){
        	int m = matrix.length;
        	if(m==0) return;
        	int n = matrix[0].length;
        	if(m<=n && m%2==1 && k==m/2+1) return;
            if(m<=n && m%2==0 && k==m/2) return;
        	if(m>n && n%2==1 && k==n/2+1) return;
            if(m>n && n%2==0 && k==n/2) return;
        	for(int j=k; j<n-k; j++){
        		res.add(matrix[k][j]);
        	}
        	for(int i=k+1; i<m-k; i++){
        		res.add(matrix[i][n-k-1]);
        	}
        	for(int j=n-k-2; j>=k; j--){
        		if(m-k-1==k) return;
        		res.add(matrix[m-k-1][j]);
        	}
        	for(int i=m-k-2; i>k; i--){
        	    if(k==n-k-1) return;
        		res.add(matrix[i][k]);
        	}
        	helper(matrix, k+1, res);
        	return;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.