leetcode 059 —— Spiral Matrix II

来源:互联网 发布:java api 1.7 手机版 编辑:程序博客网 时间:2024/06/05 03:33

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 ]]

思路:从外圈加到内圈


class Solution {public:vector<vector<int>> generateMatrix(int n) {vector<vector<int>> res(n, vector<int>(n, 0));res[0][0] = 1;for (int i = 0; i < ((n+1) / 2); i++){for (int j = i; j < n - i-1; j++){if (i==0&&j==0)res[0][0] = 1;elseres[i][j] = res[i][j - 1] + 1;res[j][n - 1 - i] = res[i][j] + n - 1 - 2 * i;  res[n - 1 - i][n - 1 - j] = res[j][n - 1 - i] + n - 1 - 2 * i;res[n - 1 - j][i] = res[n - 1 - i][n - 1 - j] + n - 1 - 2 * i;}}if (n % 2&&n>1)  //如果是奇数圈,则将中心补齐res[n / 2][n / 2] = res[n / 2][n / 2 - 1]+1;return res;}};


0 0
原创粉丝点击