Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

螺旋矩阵 II #60

Open
louzhedong opened this issue Sep 14, 2018 · 0 comments
Open

螺旋矩阵 II #60

louzhedong opened this issue Sep 14, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第59题

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

思路

同螺旋矩阵

解答

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function (n) {
  var result = [];
  for (var i = 0; i < n; i++) {
    result[i] = [];
  }
  var row = n - 1;
  var col = n - 1;
  var r = 0;
  var c = 0;
  var current = 1;
  while (r <= row && c <= col) {
    for (var i = r; i <= col; i++) {
      result[r][i] = current++;
    }
    r++;
    for (var i = r; i <= row; i++) {
      result[i][col] = current++;
    }
    col--;
    if (r <= row) {
      for (var i = col; i >= c; i--) {
        result[row][i] = current++;
      }
      row--;
    }
    if (c <= col) {
      for (var i = row; i >= r; i--) {
        result[i][c] = current++;
      }
      c++;
    }
  }

  return result;
};

console.log(generateMatrix(3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant