3-5 力扣顺序打印矩阵

在这里插入图片描述
思路:
1、规定4个方向数组 决定下一次的前进方向
2、建立访问数组,标记每个数组是否访问过

注意改变前进方向的条件(下一个数组行超限 || 列超限(>=len || <0) || 下一个位置遍历过)

class Solution {
    
    
    public int[] spiralOrder(int[][] matrix) {
    
    
        if(matrix.length==0||matrix[0].length==0){
    
    
            return new int[0];
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int total = row*col;
        int[] ans = new int[total];
        int[][] dir = {
    
    {
    
    0, 1}, {
    
    1, 0}, {
    
    0, -1}, {
    
    -1, 0}};
        boolean[][] been = new boolean[row][col];
        int directionindex = 0;
        int row0 = 0;
        int col0 = 0;
        for(int i=0; i<total; i++){
    
    
            ans[i] = matrix[row0][col0];
            been[row0][col0] = true;
            int next0 = row0+dir[directionindex][0];
            int next1 = col0+dir[directionindex][1];
            if(next0<0||next0>=row||next1>=col||next1<0||been[next0][next1]==true){
    
    
                directionindex++;
                if(directionindex==4) directionindex=0;
            }
            row0 = row0 + dir[directionindex][0];
            col0 = col0 + dir[directionindex][1];

        }
        return ans;
    }
}

复习对称二叉树
镜像二叉树

猜你喜欢

转载自blog.csdn.net/qq_40310710/article/details/114419145