Leetcode#59||Spiral Matrix II

来源:互联网 发布:调酒师动漫知乎 编辑:程序博客网 时间:2024/04/29 17:32


public class Solution {    public int[][] generateMatrix(int n) {        int[][] result = new int[n][n];                int t= 0;        int cnt = 1;                while (t < n / 2) {            // top            for (int j = t; j < n - t - 1; j++) {                result[t][j] = cnt++;            }            // right            for (int i = t; i < n - t - 1; i++) {                result[i][n - t - 1] = cnt++;            }            // bottom            for (int j = n - t - 1; j > t; j--) {                result[n - t - 1][j] = cnt++;            }            // left            for (int i = n - t - 1; i > t; i--) {                result[i][t] = cnt++;            }                        t++;        }                if (n % 2 == 1) {            result[n / 2][n / 2] = cnt;        }                return result;    }}


0 0
原创粉丝点击