【Leetcode】Spiral Matrix II (Rotated)

来源:互联网 发布:特殊字体生成器软件 编辑:程序博客网 时间:2024/06/06 18:43

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

这道题让螺旋存入数据,和I几乎差不多,唯一的不同在于不存在只有一行或一列的情况,因为是n-square的,所以只有n为奇数的时候会多出中间的元素,所以可以先把中间的元素先解决了,然后再处理其他的,思路和I差不多,如有不懂可以去参考I

public int[][] generateMatrix(int n) {int[][] result = new int[n][n];int row = n;int col = n;int x = 0;int y = 0;int num = 1;if (n % 2 != 0)result[n / 2][n / 2] = n * n;while (row > 0 && col > 0) {for (int i = 0; i < col - 1; i++)result[x][y++] = num++;for (int i = 0; i < row - 1; i++)result[x++][y] = num++;for (int i = 0; i < col - 1; i++)result[x][y--] = num++;for (int i = 0; i < row - 1; i++)result[x--][y] = num++;row = row - 2;col = col - 2;x++;y++;}return result;}



0 0
原创粉丝点击