zoukankan      html  css  js  c++  java
  • LeetCode OJ 59. 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 ]
    ]

    【题目分析】

    与Spiral Matrix不同,这个题目要求生成一个方阵,方阵的值是螺旋递增的。


    【思路】

    其实这个题目与上一个大同小异,他们遍历矩阵的顺序是相同的,只要把取值变为赋值就可以了。


    【java代码】

     1 public class Solution {
     2     public int[][] generateMatrix(int n) {
     3         int[][] matrix = new int[n][n];
     4 
     5         int top = 0;
     6         int bottom = n-1;
     7         int left = 0;
     8         int right = n-1;
     9         int num = 1;
    10 
    11         while(true){
    12             for(int i = left; i <= right; i++) matrix[top][i] = num++;
    13             top++;
    14             if(left > right || top > bottom) break;
    15 
    16             for(int i = top; i <= bottom; i++) matrix[i][right] = num++;
    17             right--;
    18             if(left > right || top > bottom) break;
    19 
    20             for(int i = right; i >= left; i--) matrix[bottom][i] = num++;
    21             bottom--;
    22             if(left > right || top > bottom) break;
    23 
    24             for(int i = bottom; i >= top; i--) matrix[i][left] = num++;
    25             left++;
    26             if(left > right || top > bottom) break;
    27         }
    28 
    29         return matrix;
    30     }
    31 }
  • 相关阅读:
    HDU 2586 How far away?
    UVAlive 5796 Hedge Mazes
    HDU 4975 A simple Gaussian elimination problem.
    Poj 1149 PIGS
    HDU 3416 Marriage Match IV
    HDU 4912 Paths on the tree
    HDU 3277 Marriage Match III
    終於記起了帳號密碼
    codeforces194a
    codeforces195c
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5532439.html
Copyright © 2011-2022 走看看