首页 > 学院 > 开发设计 > 正文

leetcode 59. Spiral Matrix II

2019-11-06 06:35:45
字体:
来源:转载
供稿:网友
package com.bupt;//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[][] result = new int[n][n];		 int number = 1;		 int minLength = 0;		 int maxLength = n-1;		 while(number<=n*n){			 int index = minLength;			 while(index <= maxLength){				 result[minLength][index] = number;				 number++;				 index++;			 }			 minLength++;			 index = minLength;			 while(index<=maxLength){				 result[index][maxLength] = number;				 number++;				 index++;			 }			 maxLength--;			 minLength--;			 index = maxLength;			 while(index>=minLength){				 result[maxLength+1][index] = number;				 number++;				 index--;			 }			 minLength++;			 index = maxLength;			 while(index>=minLength){				 result[index][minLength-1] = number;				 number++;				 index--;			 }		 }		 return result;	 }        public static void main(String[] args){    	Solution s = new Solution();    	int[][] output = s.generateMatrix(1);    	for(int i = 0;i<output.length;i++){    		for(int j = 0;j<output.length;j++){    			System.out.PRint(output[i][j]);    		}    		System.out.println();    	}    }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表