1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package com.demo.s54;
import java.util.ArrayList; import java.util.List;
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> ret = new ArrayList(); if(matrix == null || matrix.length ==0 || matrix[0].length ==0) { return ret; } int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int m = matrix.length; int n = matrix[0].length; int[][] visited = new int[m][n]; int i =0; int j =0; int directions = 0; for(int cnt = 0; cnt < m*n; cnt++) { visited[i][j] = 1;
ret.add(matrix[i][j]);
int nexti = i + dirs[directions][0]; int nextj = j + dirs[directions][1]; if(nexti < 0 || nexti > m-1 || nextj < 0 ||nextj > n-1 || visited[nexti][nextj] == 1 ) { directions = (directions+1) % 4; } i = i + dirs[directions][0]; j = j + dirs[directions][1];
} return ret; } }
|