Topic describes
(Path cycle method)
- The so-called path cycle is that the path itself has a cycle, that is, each time clockwise is a cycle, each cycle after an edge, it is necessary to modify the corresponding boundary conditions, until the cycle has gone through all the nodes.
- A picture is worth a thousand words. Sometimes many descriptions are not as clear as a picture.
- The specific idea comes from the following solution of this problem
- Answer key
The problem solving code
var spiralOrder = function(matrix) {
/ /! There is a loop in the path:
// Loop (left -- > right, up -- > Down, right -- > Left, down -- > Up)
// If the array is empty
if (matrix.length === 0) return [];
// Define four Pointers
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
// Define an array to store the final result
let res = [];
// The outermost loop is the loop that controls the number of clockwise turns
while (1) {
/ / left - > right
for (let i = left; i <= right; i++) {
res.push(matrix[top][i]);
}
top++;
if (top > bottom) break;
/ / -- >
for (let i = top; i <= bottom; i++) {
res.push(matrix[i][right]);
}
right--;
if (right < left) break;
/ / -- > left right
for (let i = right; i >= left; i--) {
res.push(matrix[bottom][i]);
}
bottom--;
if (bottom < top) break;
/ / -- >
for (let i = bottom; i >= top; i--) {
res.push(matrix[i][left]);
}
left++;
if (left > right) break;
}
return res
};
Copy the code
Conclusion (this topic gives us the enlightenment of thinking)
- Lesson 1: Learn to add boundary conditions to loops
- Lesson 2: Learn to read hidden loop conditions in questions