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(); } }}
新闻热点
疑难解答