zoukankan      html  css  js  c++  java
  • leetcode 54 螺旋矩阵

    LeetCode 54 螺旋矩阵

    在给定矩阵中,以螺旋的顺序(右->下->左->上->右)遍历所有元素并输出
    方法: 方向数组

    • 方向数组中存储一组与方向向量,每个方向上遍历过程需要用到该方向的方向向量来完成坐标的转换
    • 方向数组中的所有方向向量以循环的方式被使用,切换的条件是该方向的遍历到达边界:row-1<0; row+1=rows; col-1<0; col+1=cols; 下一元素已访问
    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> order = new ArrayList<Integer>();      //输出
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return order;
            }
            int rows = matrix.length, columns = matrix[0].length;
            boolean[][] visited = new boolean[rows][columns];
            int total = rows * columns;      //遍历元素个数达到total,结束遍历
            int row = 0, column = 0;
            int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};      //方向矩阵: 右、下、左、上
            int directionIndex = 0;
            for (int i = 0; i < total; i++) {
                order.add(matrix[row][column]);
                visited[row][column] = true;
                //该方向是否遍历结束,方向切换(循环方式)
                int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
                if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
                    directionIndex = (directionIndex + 1) % 4;
                }
                //坐标切换(求下一遍历坐标)
                row += directions[directionIndex][0];
                column += directions[directionIndex][1];
            }
            return order;
        }
    }
    
  • 相关阅读:
    量化平台的发展转
    jmeter全面总结8jmeter实战
    月见笔谈【一】——关于悲剧
    为什么要不断接触和学习新技术之我见
    WPF后台动态调用样式文件
    WPF后台动态添加TabItem并设置样式
    SQL查询SQLSERVER数据库中的临时表结构脚本
    防抖功能的实现
    项目中自定义进度条的实现
    vue3 请求响应拦截
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13298774.html
Copyright © 2011-2022 走看看