zoukankan      html  css  js  c++  java
  • LeetCode--Spiral Matrix

    题目:Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    For example,
    Given the following matrix:

    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    

    You should return [1,2,3,6,9,8,7,4,5].

    注意:是螺旋形,不是S形!

    特点:每次运动时,要么行不变,要么列不变;

    代码思路很好!!!

    代码:

    package leetcode;

    import java.util.ArrayList;
    import java.util.List;

    public class CorrectSpiralMatrix {

        public static List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> list = new ArrayList<>();
            if (matrix == null || matrix.length < 1) {
                return list;
            }
            int m = matrix.length;
            int n = matrix[0].length;
            if (m == 1 && n == 1) {
                list.add(matrix[0][0]);
                return list;
            }
            int dir = 0;
            int top = 0, right = n-1, left = 0, buttom = m-1;     //对应的行数,列数应该一致;

            while (top <= buttom && left <= right) {              //0,1,2,3代表四个方向!
                if (dir == 0) {
                    for (int i = left; i <= right; i++) {
                        list.add(matrix[top][i]);
                    }
                    top++;
                }
                if (dir == 1) {
                    for (int i = top; i <= buttom; i++) {
                        list.add(matrix[i][right]);
                    }
                    right--;
                }

                if (dir == 2) {
                    for (int i = right; i >= left; i--) {
                        list.add(matrix[buttom][i]);
                    }
                    buttom--;
                }
                if (dir == 3) {
                    for (int i = buttom; i >= top; i--) {
                        list.add(matrix[i][left]);
                    }
                    left++;
                }
                dir = (dir + 1) % 4;       //更改方向!
            }
            return list;
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[][] arr = { { 1, 2, 3 ,4,5,6}, { 7,8, 9,10,11,12 }, { 12,13,14,15,16,17 } };
            Long long1 = System.currentTimeMillis();
            System.out.print(spiralOrder(arr));
            Long long2 = System.currentTimeMillis();
            Long long3 = long2 - long1;
            System.out.println("耗时" + long3 + "毫秒!");
        }

    }
    教训:为什么不能用回溯?

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    HBase 高性能加入数据
    Please do not register multiple Pages in undefined.js 小程序报错的几种解决方案
    小程序跳转时传多个参数及获取
    vue项目 调用百度地图 BMap is not defined
    vue生命周期小笔记
    解决小程序背景图片在真机上不能查看的问题
    vue项目 菜单侧边栏随着右侧内容盒子的高度实时变化
    vue项目 一行js代码搞定点击图片放大缩小
    微信小程序进行地图导航使用地图功能
    小程序报错Do not have xx handler in current page的解决方法
  • 原文地址:https://www.cnblogs.com/neversayno/p/5263722.html
Copyright © 2011-2022 走看看