My simple java solution, easy to understand


  • 0
    H
    public List<Integer> spiralOrder(int[][] matrix) {
    	int row = matrix.length - 1;
    	if (row < 0)
    		return Collections.EMPTY_LIST;
    	int col = matrix[0].length - 1;
    	List<Integer> l = new ArrayList<Integer>(row + 1 * col + 1);
    	int r = 0, c = 0;
    	while (r <= row && c <= col) {
            //go left
    		for (int i = c; i <= col; i++) {
    			l.add(matrix[r][i]);				
    		}
    		r++;
            //go down
    		for (int i = r; i <= row; i++) {
    			l.add(matrix[i][col]);				
    		}
    		col--;
    
    		if (r <= row && c <= col) {
    			//go right
                for (int i = col; i >= c; i--) {
    				l.add(matrix[row][i]);					
    			}
    			row--;
                //go up
    			for (int i = row; i >= r; i--) {
    				l.add(matrix[i][c]);
    			}
    			c++;
    		}
    	}
    	return l;
    }

Log in to reply
 

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