Simple and easy to understand solution


  • 0
    J
    import java.awt.Point;
    import java.util.*;
    
    public class Solution {
    	public List<Integer> spiralOrder(int[][] matrix) {
    		List<Integer> list = new ArrayList<Integer>();
    		if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
    			return list;
    
    		int m = matrix.length;
    		int n = matrix[0].length;
    
    		Point[] incr = new Point[] { new Point(0, 1), new Point(1, 0), new Point(0, -1), new Point(-1, 0) };
    
    		int counter = 0, i = 0;
    		int maxRow = m - 1, maxCol = n - 1;
    		int minRow = 0, minCol = 0;
    		int curRow = 0, curCol = -1;
    
    		while (counter < m * n) {
    			int tmpCol = curCol + incr[i].y;
    			int tmpRow = curRow + incr[i].x;
    			if (tmpCol <= maxCol && tmpCol >= minCol && tmpRow <= maxRow && tmpRow >= minRow) {
    				list.add(matrix[tmpRow][tmpCol]);
    				counter++;
    				curRow = tmpRow;
    				curCol = tmpCol;
    			} else {
    				if (incr[i].y == 1)
    					minRow++;
    				else if (incr[i].y == -1)
    					maxRow--;
    				else if (incr[i].x == 1)
    					maxCol--;
    				else if (incr[i].x == -1)
    					minCol++;
    
    				i = (i + 1) % incr.length;
    			}
    		}
    
    		return list;
    	}
    }

Log in to reply
 

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