59. Spiral Matrix II

一、题目

  1、审题

 

  2、分析

    给一个正整数 n,生成 nXn 的矩阵数组,其中数组值为从 1 开始的旋转增加的数值。

二、解答

  1、思路:

    与 54 题思路类似。

     ①、从左向右、右向左时需要判断 top 是否小与 bottom;

      ②、从上到下、下到上时需要判断 left 是否 小与 right。

    注意: 题目中说生成正矩阵,所以 ①、②的判断可以省略。

public int[][] generateMatrix(int n) {
        
        int[][] arr = new int[n][n];
        int num = 1;
        
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        
        while(left <= right && top <= bottom) {
            
            for (int i = left; i <= right; i++) {
                arr[top][i] = num++;
            }
            top++;

            
            for (int i = top; i <= bottom; i++) {
                arr[i][right] = num++;
            }
            right--;
            
            //if(top <= bottom) {
                for (int i = right; i >= left; i--) {
                    arr[bottom][i] = num++;
                }
                bottom--;
            //}
            
            //if(left <= right) {
                for (int i = bottom; i >= top; i--) {
                    arr[i][left] = num++;
                }
                left++;
            //}
        }
   return arr;
    }
    
原文地址:https://www.cnblogs.com/skillking/p/9660790.html