LeetCode#54. Spiral Matrix

来源:互联网 发布:淘宝手机端怎么排名 编辑:程序博客网 时间:2024/05/16 04:20
  • 题目:一个二维数组瞬时间绕圈走,将经过的数组元素以List返回(spider order)
  • 难度:Medium
  • 思路:一开始看到题目没有很清楚spider order是什么顺序,但是猜想是绕圈,然后去看了眼别人对题目的解说。主要思路:分别求出四个方向经过的元素(同一个下标不能走两次),从外圈然后到内圈,是一个递归的过程,只需要调整起始位置和剩余遍历的行列数
  • 代码:
public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> result = new ArrayList<Integer>();        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){            return result;        }        int lenX = matrix.length;        int lenY = matrix[0].length;        helper(matrix, 0, 0, lenX, lenY, result);        return result;    }    private void helper(int[][] matrix, int startX, int startY, int rows, int cols, List<Integer> list){        if(rows <= 0 || cols <= 0){            return ;        }        System.out.println(rows + "-" + cols);        System.out.println(startX + "-" + startY);        //上面的行        for(int i = 0; i < cols; i++){            list.add(matrix[startX][startY+i]);        }        //右边的列        for(int i=1; i < rows-1; i++){            list.add(matrix[startX+i][startY+cols-1]);        }        //下面的行        if(rows > 1){            for(int i = 0; i < cols; i++){                list.add(matrix[startX+rows-1][startY+cols-1-i]);            }        }        //左边的列        if(cols > 1){            for(int i=1; i < rows-1; i++){                list.add(matrix[startX+rows-1-i][startY]);            }        }        helper(matrix,startX+1, startY+1,rows-2,cols-2,list);    }}

定义rowsBegin,rowsEnd, colsBegin, colsEnd四个变量,用while循环遍历spiral matrix

public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> result = new ArrayList<>();        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){            return result;        }        int rowsBegin = 0;        int colsBegin = 0;        int rowsEnd = matrix.length-1;        int colsEnd = matrix[0].length-1;        while(rowsBegin <= rowsEnd && colsBegin <= colsEnd){            for(int i = colsBegin; i <= colsEnd; i++){                result.add(matrix[rowsBegin][i]);            }            rowsBegin++;            for(int i = rowsBegin; i < rowsEnd; i++){                result.add(matrix[i][colsEnd]);            }            colsEnd--;            //下面的行            if(rowsEnd-rowsBegin+1 > 0){                for(int i = colsEnd+1; i >= colsBegin; i--){                    result.add(matrix[rowsEnd][i]);                }            }            rowsEnd--;            //左边的列            if(colsEnd-colsBegin+1 > 0){                for(int i = rowsEnd; i >= rowsBegin; i--){                    result.add(matrix[i][colsBegin]);                    System.out.println(matrix[i][colsBegin]);                }            }            colsBegin++;        }        return result;    }}
0 0