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 ]
    ]
    
    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 }
  • 相关阅读:
    ChukWa入门1
    asp.net常用代码集锦
    泛型讲解
    深入宠物店PetShopSQLServerDAL数据访问与SampleDuwamish比较
    写有效率的SQL查询(转载)
    VisualStudio2005技巧集合
    iptables总结【转载】
    vmware workstation 如何注册
    4.继承
    Linux系统下源代码包方式 安装前准备[1]
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4102806.html
Copyright © 2011-2022 走看看