• leetcode -- Spiral Matrix II


    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example,
    Given n = 3,

    You should return the following matrix:

    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]

    java 中是传值的,将count作为返回值返回

     1 public static int[][] generateMatrix(int n) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         if(n <= 0)
     5             return new int[0][];
     6         
     7         int rows = n;
     8         int cols = n;
     9         int[][] result = new int[n][n];
    10         int count = 1;
    11         
    12         int start = 0;
    13         while (rows > start * 2 && cols > start * 2) {
    14             count = printCircle(result, rows, cols, start, count, n * n);
    15             start++;
    16         }
    17         
    18         return result;
    19     }
    20     
    21     public static int printCircle(int[][] matrix, int rows, int cols,
    22             int start, int count, int n) {
    23         int endX = cols - 1 - start;
    24         int endY = rows - 1 - start;
    25 
    26         // print row
    27         for (int i = start; i <= endX && count <= n; i++) {
    28             matrix[start][i] = count ++;
    29         }
    30 
    31         // print col
    32         if (endY > start) {
    33             for (int i = start + 1; i <= endY && count <= n; i++) {
    34                 matrix[i][endX] = count ++;
    35             }
    36         }
    37         // print row
    38         if (endX > start && endY > start) {
    39             for (int i = endX - 1; i >= start && count <= n; i--) {
    40                 matrix[endY][i] = count ++;
    41             }
    42         }
    43         // print col
    44         if (endX > start && endY - 1 > start) {
    45             for (int i = endY - 1; i > start && count <= n; i--) {
    46                 matrix[i][start] = count ++;
    47             }
    48         }
    49         return count;
    50     }
  • 相关阅读:
    advanceInstaller安装文件的ICON
    advanceInstaller制作中文安装界面
    vc对话框程序运行时隐藏
    VC++6.0 打印调试信息
    js使用正则表达式实现文本框只能输入数字和小数点
    Flexbox制作CSS布局实现水平垂直居中
    微信js SDK接口
    QQ JS_SDk相关功能接口
    github代码管理工具的使用方法
    webpack打包压缩工具的使用方法
  • 原文地址:https://www.cnblogs.com/feiling/p/3244744.html
Copyright © 2020-2023  润新知