lintcode-medium-Spiral Matrix II
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Spiral Matrix II相关的知识,希望对你有一定的参考价值。
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
Example
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution { /** * @param n an integer * @return a square matrix */ public int[][] generateMatrix(int n) { // Write your code here if(n == 0) return new int[0][0]; int[][] res = new int[n][n]; int[] num = new int[1]; num[0] = 1; for(int i = 0; i < n / 2; i++) helper(res, i, num); if(n % 2 == 1) res[n / 2][n / 2] = num[0]; return res; } public void helper(int[][] res, int layer, int[] num){ int n = res.length; int start = layer; int end = n - layer - 1; if(start == end){ res[start][start] = num[0]; return; } for(int i = 0; i < end - start; i++){ res[start][start + i] = num[0]; num[0] = num[0] + 1; } for(int i = 0; i < end - start; i++){ res[start + i][end] = num[0]; num[0] = num[0] + 1; } for(int i = 0; i < end - start; i++){ res[end][end - i] = num[0]; num[0] = num[0] + 1; } for(int i = 0; i < end - start; i++){ res[end - i][start] = num[0]; num[0] = num[0] + 1; } return; } }
以上是关于lintcode-medium-Spiral Matrix II的主要内容,如果未能解决你的问题,请参考以下文章