Topic describes
Their thinking
- First define four Pointers as shown in the figure below:
-
According to the clockwise traversal, respectively from left to right, from top to bottom, from right to left, from bottom to top.
-
After one loop, let the left pointer +1 to continue the next loop, and notice that each time you move the pointer, you need to pay attention to whether the pointer is out of bounds.
var spiralOrder = function(matrix) {
// The core of the spiral matrix is to use four Pointers to assist traversal
If the length of the matrix is 0, return an empty array
if (matrix.length === 0) return [];
// Define four Pointers
let left = 0;
let top = 0;
let right = matrix[0].length - 1;
let bottom = matrix.length - 1;
// Define the final result returned
const res = [];
// Start traversal
while (1) {
// It is mainly clockwise traversal
// Step 1: from left to right
for (let i = left; i <= right; i++) {
res.push(matrix[top][i])
}
// Step 2: From top to bottom
top++;
if (top > bottom) break;
for (let i = top; i <= bottom; i++) {
res.push(matrix[i][right]);
}
// Step 3: From right to left
right--;
if (right < left) break;
for (let i = right; i >= left; i--) {
res.push(matrix[bottom][i])
};
// Step 4: Start from bottom to top
bottom--;
if (bottom < top) break;
for (let i = bottom; i >= top; i--) {
res.push(matrix[i][left])
}
// Step 5: The most forgotten step
left++;
if (left > right) break;
}
return res;
};
Copy the code
The title to reflect
Helical matrix and clockwise print matrix are the same topic, this topic has appeared in both the finger Offer and many interview occasions, so we must understand this topic, the essence is pointer assisted plus conditional judgment.