题解 | #螺旋矩阵(二)#
螺旋矩阵(二)
https://www.nowcoder.com/practice/2c8078a728834e81a046fdefdea049aa
using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return int整型二维数组 */ public List<List<int>> Matrix (int n) { //write code here if (n == 0) return null; if (n == 1) return new List<List<int>>() { new List<int>() { 1 } }; List<List<int>> nArr = new List<List<int>>(); for (int i = 0; i < n; i++) { List<int> lsN = new List<int>(); nArr.Add(lsN); for (int j = 0; j < n; j++) lsN.Add(0); } int nI = 0, nJ = 0, nN = 1; while (nN <= n * n) { //j++ while (nJ < n && nArr[nI][nJ] == 0) { nArr[nI][nJ] = nN; nN++; nJ++; } nJ--; nI++; //i++ while (nI < n && nArr[nI][nJ] == 0) { nArr[nI][nJ] = nN; nN++; nI++; } nI--; nJ--; //j-- while (nJ >= 0 && nArr[nI][nJ] == 0) { nArr[nI][nJ] = nN; nN++; nJ--; } nJ++; nI--; //i-- while (nI >= 0 && nArr[nI][nJ] == 0) { nArr[nI][nJ] = nN; nN++; nI--; } nI++; nJ++; } return nArr; } }