My Simple Java Solusion


  • 0
    M
    public List<Integer> spiralOrder(int[][] matrix) {
    	List<Integer> list = new ArrayList<>();
            if (matrix == null || matrix.length == 0) return list;
    		int m = matrix.length, n = matrix[0].length;
    		if (n == 0) return list;
    		int[][] d = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    		int dInd = 0;
    		boolean[][] added = new boolean[m][n];
    		int i=0, j=0;
    		while (true) {
    			if (i < 0 || i >= m || j < 0 || j >= n || added[i][j]) {
    				i -= d[dInd][0];
    				j -= d[dInd][1];
    				dInd = (dInd + 1) % d.length;
    				i += d[dInd][0];
    				j += d[dInd][1];
    				if (i < 0 || i >= m || j < 0 || j >= n || added[i][j]) {
    				    break;
    				}
    			} else {
    				list.add(matrix[i][j]);
    				added[i][j] = true;
    				i += d[dInd][0];
    				j += d[dInd][1];
    			}
    		}
    		return list;
        }
    

Log in to reply
 

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