zoukankan      html  css  js  c++  java
  • JZ19 顺时针打印矩阵

    描述

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵:
    [[1,2,3,4],
    [5,6,7,8],
    [9,10,11,12],
    [13,14,15,16]]
    则依次打印出数字
    [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

    示例1

    输入:
    [[1,2],[3,4]]
    返回值:
    [1,2,4,3]


    ===========================================================================================================================================


    解题思路:((n - 1) > 2 * i)
      本题是通过判断行列哪一个短,哪一个短,就用哪一个可以得到最低的顺时针打印次数,再依次打印每个边,注意要在判断条件中加上当前((n - 1) > 2 * i)是为了防止行列值差距过大,从而导致重复打印。

    代码:
      
    import java.util.ArrayList;
    public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
    ArrayList<Integer> res = new ArrayList<>();
    if(matrix.length == 0 || matrix[0].length == 0)return res;
    int n = matrix.length, m = matrix[0].length;
    if(n == 1){
    for(int vals : matrix[0])res.add(vals);
    return res;
    }else if(m == 1){
    for(int i = 0; i < n; i ++)
    res.add(matrix[i][0]);
    return res;
    }
    int t = n >= m? m : n;
    int q = t % 2 == 0 ? t/2 : t/2 + 1;

    for(int i = 0; i < q; i ++){
    //从左往右打印
    for(int j = i; j < m - i; j ++)
    res.add(matrix[i][j]);
    //从上往下打印
    for(int j = i + 1; j < n - i; j ++)
    res.add(matrix[j][m - i - 1]);
    //从左往右打印
    for(int j = m - i - 2; j > i && ((n - 1) > 2 * i); j --)
    res.add(matrix[n - i - 1][j]);
    //从下往上打印
    for(int j = n - i - 1; j > i && ((m - 1) > 2 * i); j --)
    res.add(matrix[j][i]);
    }
    return res;
    }
    }


  • 相关阅读:
    Invalid bound statement (not found)解决方法
    MySQL的sum()函数
    关于Mybatis的java.lang.UnsupportedOperationException异常处理
    博客迁移
    Building Blog(个性化博客)2
    走一波服务器
    JZ高中OJ 1036. [SCOI2009]迷路
    JZ初中OJ 2296. [noip普及组2]神殿
    JZ初中OJ 2295. [noip普及组2]栈
    JZ初中OJ 2298. [noip普及组2]异或
  • 原文地址:https://www.cnblogs.com/hddandelion/p/15207370.html
Copyright © 2011-2022 走看看