• 【面试题20】顺时针打印矩阵


    【题目描述】

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

    【测试用例】

    1. 多行数组;

    2. 只有一行的数组;

    3. 只有一列的数组;

    4. 只有一行一列的数组;

    【解决方案】

    本题没有涉及复杂的算法或数据结构,画图可以让本题的思路更加具体化,考察动手画图用自己的思维解决问题的思路,只是考虑的问题稍多,并不难。

    1. 考虑顺时针各个行列的打印规律;

    2. 考虑不规则的打印情况;

    我的代码实现,仅供参考:

     1         public static void PrintMatrixClockWisely(int[][] arr)
     2         {
     3             if (arr == null || arr[0] == null)
     4             {
     5                 return;
     6             }
     7 
     8             int left = 0;
     9             int right = arr[0].Length - 1;
    10             int top = 0;
    11             int bottom = arr.GetLength(0) - 1;
    12 
    13             while (left <= right && bottom >= top)
    14             {
    15                 //打印上边一行
    16                 for (int i = left; i <= right; i++)
    17                 {
    18                     Console.WriteLine(arr[top][i]);
    19                 }
    20 
    21                 //打印右边一列
    22                 if (top < bottom)
    23                 {
    24                     for (int i = top + 1; i <= bottom; i++)
    25                     {
    26                         Console.WriteLine(arr[i][right]);
    27                     }
    28                 }
    29 
    30                 //打印下边一行
    31                 if (left < right && top < bottom)
    32                 {
    33                     for (int i = right - 1; i >= left; i--)
    34                     {
    35                         Console.WriteLine(arr[bottom][i]);
    36                     }
    37                 }
    38 
    39                 //打印左边一列
    40                 if (left < right && top < bottom - 1)
    41                 {
    42                     for (int i = bottom - 1; i > top; i--)
    43                     {
    44                         Console.WriteLine(arr[i][left]);
    45                     }
    46                 }
    47 
    48                 left++;
    49                 right--;
    50                 top++;
    51                 bottom--;
    52             }
    53         }
  • 相关阅读:
    socket server的N种并发模型
    进程、线程以及Goroutine的区别
    分布式从ACID、CAP、BASE的理论推进
    epoll的理论与IO阻塞机制
    golang面试题知识点总结
    golang中如何进行项目模块及依赖管理
    面对golang中defer,要注意什么?
    Kaggle 学习之旅
    推荐在线学习读书网站
    k8s 的 dashboard 的实践
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4803970.html
Copyright © 2020-2023  润新知