One Pager Cheat Sheet
- Print the elements of an
m * n
matrix array in a spiral order, usingO(1)
space andO(n*m)
time complexity, with all values between-1000000000
and1000000000
. - Traversing an
m * n
matrix in spiral order requires transitioning from the outer rings to the inner rings, while keeping track of the outer left and right columns, and the upper and bottom rows, withcolLower
,colUpper
,rowLower
, androwUpper
variables. - We can traverse an entire matrix in spiral order by following an algorithm of moving right, then down, then left, then up, and incrementing
rowLower
and decrementingcolUpper
after each iteration. - The algorithm to traverse an
m * n
matrix in spiral order has a linear time complexity and fixed space complexity ofO(1)
.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
78
}
var assert = require('assert');
​
function spiraltraverse(inmatrix) {
if (!inmatrix.length) return [];
const res = [];
const dirs = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
const scope = [inmatrix[0].length, inmatrix.length - 1];
let d = 0,
r = 0,
c = -1;
while (scope[d % 2] > 0) {
for (let i = 0; i < scope[d % 2]; i++) {
r += dirs[d][0];
c += dirs[d][1];
res.push(inmatrix[r][c]);
}
scope[d % 2]--;
d = (d + 1) % 4;
}
return res;
}
​
try {
assert.equal(
spiraltraverse([
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.