Why it works
- An O is safe exactly when it is joined to an O on the border, so walking in from the border O cells marks every safe O and nothing else.
- Checking each O on its own would mean a separate search per cell; one walk from the border settles all of them at once.
- The mark K keeps the walk from entering a cell twice and tells the second pass which O cells to keep.
Complexity
Time O(rows × cols): keep enters each cell at most once, and the second pass looks at each cell once. Memory O(rows × cols) at worst, for the call stack.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗