• 顺时针打印数组


    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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

    一直说我数组越界,后来仔细改改总算对了,但是我觉得我的那个最外边的循环条件好像有问题

    借助了visted数组记录

     1 import java.util.ArrayList;
     2 public class Solution {
     3     public ArrayList<Integer> printMatrix(int [][] matrix) {
     4         ArrayList<Integer> res=new ArrayList<Integer>();
     5         int m=matrix.length;
     6         if(m==0)
     7             return res;
     8         int n=matrix[0].length;
     9         boolean[][] visted=new boolean[m][n];
    10         for(int i=0;i<((m+1)/2);i++)
    11         {
    12             for(int top=0;top<n;top++)
    13                 if(visted[i][top]==false)
    14                 {
    15                     res.add(matrix[i][top]);
    16                     visted[i][top]=true;
    17                 }
    18             for(int right=0;right<m&&(n-1-i)>=0;right++)
    19                 if(visted[right][n-1-i]==false)
    20                 {
    21                     res.add(matrix[right][n-1-i]);
    22                     visted[right][n-1-i]=true;
    23                 }
    24             for(int button=n-1;button>=0&&(m-1-i)>=0;button--)
    25                 if(visted[m-1-i][button]==false)
    26                 {
    27                     res.add(matrix[m-1-i][button]);
    28                     visted[m-1-i][button]=true;
    29                 }
    30             for(int left=m-1;left>=0&&i<n;left--)
    31                 if(visted[left][i]==false)
    32                 {
    33                     res.add(matrix[left][i]);
    34                     visted[left][i]=true;
    35                 }
    36         }
    37         return res;
    38     }
    39 }
  • 相关阅读:
    随机数、无重复、冒泡排序
    今天是星期几
    Button
    2012/8/5为应用指定多个配置文件
    2012/8/4解决JSP显示中文乱码
    2012/8/4 struts2学习笔记
    2012/8/4Action中result的各种转发类型
    2012/8/4为Action属性注入值
    2012/8/3SVN小入门
    2012/8/3 Extjs使用TabPanel时需要注意的问题
  • 原文地址:https://www.cnblogs.com/cold-windy/p/11536012.html
Copyright © 2020-2023  润新知