/* Solution 3: 使用方向矩阵来求解 */ public List<Integer> spiralOrder(int[][] matrix){ List<Integer> ret = new ArrayList<Integer>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return ret; } int rows = matrix.length; int cols = matrix[0].length; int visitedRows = 0; int visitedCols = 0;
// indicate the direction of x // 1: means we are visiting the row by the right direction. // -1: means we are visiting the row by the left direction. int[] x = {1, 0, -1, 0}; // 1: means we are visiting the colum by the down direction. // -1: means we are visiting the colum by the up direction. int[] y = {0, 1, 0, -1}; // 0: right, 1: down, 2: left, 3: up. int direct = 0; int startx = 0; int starty = 0; int candidateNum = 0; int step = 0; while (true) { if (x[direct] == 0) { // visit Y axis. candidateNum = rows - visitedRows; } else { // visit X axis candidateNum = cols - visitedCols; } if (candidateNum <= 0) { break; } ret.add(matrix[startx][starty]); step++; if (step == candidateNum) { step = 0; visitedRows += x[direct] == 0 ? 0: 1; visitedCols += y[direct] == 0 ? 0: 1; // move forward the direction. direct ++; direct = direct%4; } // 根据方向来移动横坐标和纵坐标。 startx += y[direct]; starty += x[direct]; } return ret; }
近期评论