• 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 ]
    ]
    
    Have you met this question in a real interview?
     
    Solution:
     1 public class Solution {
     2     public int[][] generateMatrix(int n) {
     3         int[][] matrix = new int[n][n];
     4 
     5         int[] x = new int[]{0,1,0,-1};
     6         int[] y = new int[]{1,0,-1,0};      
     7         int direction = 0;
     8         int curX = 0, curY=0;        
     9         int rowStart = 0, rowEnd = n-1, colStart=0, colEnd=n-1;
    10         int len = n*n;
    11         
    12         for (int i=0;i<len;i++){
    13             matrix[curX][curY]=i+1;    
    14             int nextX = curX+x[direction];
    15             int nextY = curY+y[direction]; 
    16             //Determin the availability of next point.
    17             if (nextX>rowEnd || nextX<rowStart || nextY>colEnd || nextY<colStart){
    18                 direction = (direction+1)%4;
    19                 nextX = curX+x[direction];
    20                 nextY = curY+y[direction];
    21                 //Update the availability of rows and cols according the direction change.
    22                 if (direction==1) rowStart++;
    23                 if (direction==2) colEnd--;
    24                 if (direction==3) rowEnd--;
    25                 if (direction==0) colStart++;
    26             }
    27             curX = nextX;
    28             curY = nextY;
    29         }
    30 
    31         return matrix;
    32 
    33     }
    34 }
  • 相关阅读:
    RESTful API 设计原则
    c#的逆变和协变
    Java内部类之间的闭包和回调详解
    java的内部类
    抓包工具
    HashMap与HashTable的区别
    Java 语法清单
    Java面试问题列表
    bootstrap table api
    c# CacheManager 缓存管理
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4102806.html
Copyright © 2020-2023  润新知