Leetcode 885: Spiral Matrix III

grid47
grid47
Exploring patterns and algorithms
Aug 10, 2024 6 min read

You are given a grid of size rows x cols, where each cell represents a coordinate. You start at a given coordinate (rStart, cStart), facing east, and your goal is to walk in a clockwise spiral through the grid. As you walk, you must visit each cell exactly once. Once you reach the boundary of the grid, continue walking outside the grid, but you may return to the grid later. Return a list of the coordinates you visit in the order you encounter them.
Problem
Approach
Steps
Complexity
Input: You are given the dimensions of the grid (rows, cols) and your starting position (rStart, cStart).
Example: Input: rows = 3, cols = 3, rStart = 1, cStart = 1
Constraints:
• 1 <= rows, cols <= 100
• 0 <= rStart < rows
• 0 <= cStart < cols
Output: You should return a list of coordinates, where each coordinate is represented as an array [r, c], in the order they were visited.
Example: Output: [[1,1],[1,2],[0,2],[0,1],[0,0],[1,0],[2,0],[2,1],[2,2]]
Constraints:
• The output should contain all coordinates visited in the spiral traversal.
Goal: The goal is to simulate the spiral traversal, carefully switching directions and ensuring no cell is skipped.
Steps:
• Start from the given position and begin moving east.
• Continue spiraling in clockwise direction, changing direction after hitting a boundary or previously visited cell.
• Use a list to keep track of the coordinates you visit.
Goal: The problem must be solved efficiently within the constraints.
Steps:
• The grid size is not larger than 100x100.
• You must return all coordinates in the order they are visited.
Assumptions:
• The grid has at least one cell.
• You can go outside the grid and return later when needed.
Input: Input: rows = 3, cols = 3, rStart = 1, cStart = 1
Explanation: The grid is 3x3 with the start position at (1,1). The spiral traversal starts at (1,1), moves east to (1,2), then north to (0,2), then west to (0,1), then south to (1,0), and continues until all cells are visited. The output is the list of coordinates visited in this order.

Input: Input: rows = 2, cols = 2, rStart = 0, cStart = 0
Explanation: The grid is 2x2 with the start position at (0,0). The spiral traversal visits (0,0), moves east to (0,1), then south to (1,1), and finally west to (1,0).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus