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

    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] a = new int[n][n];
            if(n == 0) return a;
            if(n == 1) {
                a[0][0] = 1;
                return a;
            }
            int top = 0;
            int bottom = n -1;
            int left = 0;
            int right = n - 1;
            int num = 1;
            while(top <= bottom && left <= right){
                //right to left in top
                for(int i = left ; i <= right ; i++){
                    a[top][i] = num;
                    num++;
                }
                top++;
                
                //top to bottom in right
                for(int i = top ; i <= bottom ; i++){
                    a[i][right] = num;
                    num++;
                }
                right--;
               
                // right ->  left in bottom 
                if(bottom >= top){
                    for(int i = right ; i >= left ; i--){
                        a[bottom][i] = num;
                        num++;
                    }
                    bottom--;
                }
                
                //bottom -> top in left
                if(right >= left){
                    for(int i = bottom ; i >= top ; i--){
                        a[i][left] = num;
                        num++;
                    }
                    left++;
                }
            }
            return a;
        }
    }
  • 相关阅读:
    javascript 数字格式化
    spring-cloud blogs
    rabbitmq python
    centos7下 安装mysql
    hue install
    d3 document
    elastichq 离线安装
    elasticsearch agg
    elastichq auto connect
    Go Hello World!
  • 原文地址:https://www.cnblogs.com/joannacode/p/6120829.html
Copyright © 2011-2022 走看看