• 54-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].

    【思路】

    1.按照 从右、从下、从左、从上的顺序遍历数组

    2.只需记录矩阵的四个角的坐标(需注意单行矩阵或单列矩阵)

    【算法实现】

    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res=new ArrayList<Integer>();
            int x1=0;
            int y1=0;
            int x2=matrix.length-1;
            if(x2<0)
                return res;
            int y2=matrix[0].length-1;
            while(x1<=x2&&y1<=y2) {
                for(int i=y1;i<=y2;i++)         //right
                    res.add(matrix[x1][i]);
                for(int i=x1+1;i<=x2;i++)       //down
                    res.add(matrix[i][y2]);
                if(x1!=x2) {
                    for(int i=y2-1;i>=y1;i--)   //left
                        res.add(matrix[x2][i]);    
                }
                if(y1!=y2) {
                    for(int i=x2-1;i>x1;i--)    //up 
                        res.add(matrix[i][y1]);                
                }
                x1++;
                y1++;
                x2--;
                y2--;
            }
            return res;
        }
    }
  • 相关阅读:
    CSSText属性批量修改样式
    JS 学习(四)对象
    JS 学习(三)DOM
    JS语法(二)
    JS学习笔记(一)
    CSS3属性transition
    动画期间响应事件
    仿淘宝详情转场
    HTML 滚动标签<marquee>
    Oracle MySQL Server 安全漏洞
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4444216.html
Copyright © 2020-2023  润新知