zoukankan      html  css  js  c++  java
  • 【leetcode】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].

    Tips:Input:一个m×n的二维数组,按照顺时针打印

    解决办法:每一圈递归一次。

    package medium;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class L54SpiralMatrix {
        public List<Integer> spiralOrder(int[][] matrix) {
            if (matrix == null)
                return null;
            List<Integer> ans = new ArrayList<>();
            int rows = matrix.length;
            if (rows==0) return ans;
            int cols = matrix[0].length;
            int row = 0;
            List<Integer> ans1 = spiralOrderCore(matrix, 0, rows - 1, 0, cols - 1, ans);
            return ans1;
        }
    
        private List<Integer> spiralOrderCore(int[][] matrix, int row, int rows, int col, int cols, List<Integer> ans) {
            if (row < rows && col < cols) {
                for (int c = col; c < cols; c++) {
                    ans.add(matrix[row][c]);
                }
                for (int r = row; r < rows; r++) {
                    ans.add(matrix[r][cols]);
                }
                for (int i = cols; i > col; i--) {
                    ans.add(matrix[rows][i]);
                }
                for (int i = rows; i > row; i--) {
                    ans.add(matrix[i][col]);
                }
                spiralOrderCore(matrix, row + 1, rows - 1, col + 1, cols - 1, ans);
            } else if (row == rows) {
                for (int c = col; c <=cols; c++) {
                    ans.add(matrix[row][c]);
                }
    
            } else if (col == cols) {
                for (int r = row; r <= rows; r++) {
                    ans.add(matrix[r][col]);
                }
            }
            
            return ans;
        }
    
        public static void main(String[] args) {
            System.out.println("Main start");
            int[][] matrix = { { 1, 2, 3 ,4}, {  5, 6,7, 8 }, {  9,10,11,12 } ,{13,14,15,16}};
            int[][] ma={{2,3}};
            int[][] matrix1 = { { 1, 2, 3}, {4,  5, 6},{7, 8  , 9}};
            L54SpiralMatrix l54 = new L54SpiralMatrix();
            List<Integer> ans = l54.spiralOrder(ma);
            System.out.println("size:"+ans.size());
            for (int i = 0; i <ans.size(); i++) {
                System.out.println(ans.get(i));
            }
    
        }
    }
  • 相关阅读:
    抽象类和接口【转】
    JQuery中的事件总结
    ExecuteNonQuery()返回受影响行数不适用select语句
    用js获取对象之前首先检测元素是否存在
    页面如何自动出现滚动条(overflow属性用法)
    今天调试程序遇到了一个致命问题语法错误操作符丢失
    JQuery选择器学习总结JQuery选择器
    css !important用法CSS样式使用优先级判断
    JQuery操作DOM总结
    JQuery特效与动画总结
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8418043.html
Copyright © 2011-2022 走看看