-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspiral-matrix-ii.js
More file actions
58 lines (49 loc) · 1.63 KB
/
spiral-matrix-ii.js
File metadata and controls
58 lines (49 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// https://leetcode.com/problems/spiral-matrix-ii/
// Related Topics: Array
// Difficulty: Medium
/*
Initial thoughts:
We are going to write each border of an imaginary outline clockwise
and move inward until there are no more outlines left.
To keep track of the bounderies of our borders, we will have a variable
for each boundary that we increment or decrement accordingly.
To keep track of when we have reached the end of the spiral, we will
simply track the number of elements that we have already read. When that
number equals the number of the elements in the matrix, we are done.
Time complexity: O(n^2) where n === length of a side of our square matrix
Space complexity: O(n^2) where n === length of a side of our square matrix
(that's for the results array. In some interpretations, this does not count as
auxilliary space.)
*/
/**
* @param {number} n
* @return {number[][]}
*/
const generateMatrix = n => {
if (n === 0) return [];
const result = [];
for (i = 0; i < n; i++) result.push(Array(n));
let left = (top = 0);
let right = (bottom = n - 1);
let count = 1;
const lenMatrix = n ** 2;
while (true) {
// Top
for (let i = left; i <= right; i++) result[top][i] = count++;
top++;
if (count > lenMatrix) break;
// Right
for (let i = top; i <= bottom; i++) result[i][right] = count++;
right--;
if (count > lenMatrix) break;
// Bottom
for (let i = right; i >= left; i--) result[bottom][i] = count++;
bottom--;
if (count > lenMatrix) break;
// Left
for (let i = bottom; i >= top; i--) result[i][left] = count++;
left++;
if (count > lenMatrix) break;
}
return result;
};