Watch four walls close in on a grid as it is read in spiral order. Every cell read once, nothing marked visited: O(R × C) time, O(1) extra space.
About this algorithm
Spiral order reads a grid along the top row, down the right column, back along the bottom row and up the left column, then repeats one ring further in until every cell has been read once. The standard solution keeps four walls, top, bottom, left and right, and moves one wall inward after each side is read. This is LeetCode 54.
Use the four walls method for any walk that peels a grid ring by ring: printing a matrix in spiral order, filling a grid with 1 to N² in a spiral (Spiral Matrix II), or rotating a square image layer by layer. It needs no visited marks and no search, because the walls remember what has been read. That makes it a different kind of grid walk from the BFS and DFS pages, which explore outward from a start cell and react to walls they find; the spiral path is fixed by the shape of the grid alone. The other common way steers with a direction and turns right when the next cell is off the grid or already read, which costs a visited grid.
top = 0, bottom = rows - 1, left = 0, right = cols - 1. The cells between them are the ones not read yet.
Read left to right along row top, then move top down one. Read top to bottom down column right, then move right in one.
If top has passed bottom or left has passed right, stop. Without this check, a grid with more columns than rows would read its last row a second time, backwards.
Read right to left along row bottom and move bottom up. Read bottom to top up column left and move left in. Loop while top is at most bottom and left is at most right.
The page opens on a 4 by 5 grid whose rows read PRACT, PERFI, STCEC and EKAME. The first ring reads the top row P R A C T, the right column I C E, the bottom row backwards M A K E and the left column upwards S P, spelling PRACTICE MAKES P. The walls now stand at top 1, bottom 2, left 1 and right 3. The second ring reads E R F along row 1, E down column 3, and C T back along row 2. The left column has no cells left between the walls, and the loop ends because top (2) has passed bottom (1). All 20 letters in order spell PRACTICE MAKES PERFECT. Generate New cycles through four more grids, including a 3 by 4 one where the check in step 3 is the line that stops the walk.
Time: every cell is read exactly once, and the walls move inward a total of about R + C times. Space: four integers for the walls; the output list of R × C values is the answer itself, not working memory.