zoukankan      html  css  js  c++  java
  • 【LeetCode】Spiral Matrix

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

    public class Solution {
        public ArrayList<Integer> spiralOrder(int[][] matrix) {
            ArrayList<Integer> re = new ArrayList<Integer>();
            
            if(matrix.length==0)
                return re;
            
            
            int row = matrix.length;
            int col = matrix[0].length;
            
            int start=-1;
            int end=-1;
            int temprow=row;
            int tempcol = col;
            
            while(temprow>0&&tempcol>0){
                start++;
                end++;
                //如果剩下的行数或者列数位0
                if(temprow==start||tempcol==end)
                    break;
                for(int i=start;i<tempcol;i++)
                    re.add(matrix[start][i]);
                for(int j=start+1;j<temprow;j++)
                    re.add(matrix[j][tempcol-1]);
                
                //如果剩余一行或者一列
                if((temprow-1)==start||(tempcol-1)==end)
                    break;
                for(int x=tempcol-2;x>=end;x--)
                    re.add(matrix[temprow-1][x]);
                for(int y=temprow-2;y>start;y--)
                    re.add(matrix[y][end]);
                
                temprow=temprow-1;
                tempcol=tempcol-1;
            }
            return re;
            
        }
    }
  • 相关阅读:
    文件和文件夹权限
    CentOS 8修改用户密码
    Linux新建用户默认设置
    二、工具类
    一、MyBatis 核心配置文件
    十一、容器总结
    十、Collections工具类
    九、集合与数组之间的转化
    八、TreeSet
    ※大神※
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3722199.html
Copyright © 2011-2022 走看看