An easy to understand solution


  • 0
    B

    First, go through the first row.Then, rotate the matrix by anticlockwise 90, then do the same thing :)

    public class Solution {
        int[][] step = {{0,1},{1,0},{0,-1},{-1,0}};
        void spider(int n, int m, int sg, int[][] matrix, List<Integer> res, int x, int y){
        	if(n == 0) return;
        	for(int i = 0; i < n-1; ++i){
        		res.add(matrix[x][y]);
        		x += step[sg][0]; y += step[sg][1];
        	}
        	res.add(matrix[x][y]);
        	sg = (sg + 1)%4;
        	x += step[sg][0]; y += step[sg][1];
        	spider(--m,n,sg,matrix,res,x,y);
        }
    	public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res = new ArrayList<Integer>();
            if(matrix.length==0) return res;
            spider(matrix[0].length,matrix.length, 0, matrix, res, 0, 0);
            return res;
        }
    }

Log in to reply
 

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