首页 > 代码库 > leetcode--Spiral Matrix II
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 ]]
public class Solution { public int[][] generateMatrix(int n) { int[][] result = new int[n][n]; if(n > 0){ int num = 1; for(int i = 0; i < n / 2; ++i){ for(int k = i; k < n - i; ++k){ result[i][k] = num; ++num; } for(int k = i + 1; k < n - (i + 1); ++k){ result[k][n - (i + 1)] = num; ++num; } for(int k = i; k < n - i; ++k){ result[n - 1 - i][n - 1 - k] = num; ++num; } for(int k = i + 1; k < n - (i + 1); ++k){ result[n - 1 - k][i] = num; ++num; } } if(n % 2 != 0) result[n / 2][n / 2] = num; } return result; }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。