zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    关系型数据库性能优化总结(转载)
    分区视图(转载)
    硬盘Raid
    AutoFac
    OSI各层的功能和主要协议(转载)
    Squid
    Nginx+Windows负载均衡(转载)
    Mysql命令alter add:增加表的字段
    Delphi调用WebService(通过SoapHeader认证)经验总结
    Delphi开发OCX详细步骤总结
  • 原文地址:https://www.cnblogs.com/feiling/p/3244744.html
Copyright © 2011-2022 走看看