B - 海図の航路 / Sea Chart Lanes Editorial by admin Editorial for printing
swe-2-highSolution
For each column \(j\) (\(1 \leq j \leq W\)), check whether every cell \(S_1[j], S_2[j], \ldots, S_H[j]\) in that column is .. If all of them are ., the column can be used as a sea route, so we add 1 to the answer.
Concretely, for each column we initialize a flag ok to true, scan the rows from top to bottom, and set ok to false as soon as a # is found. If no # is found after checking all rows, the column consists entirely of sea and is counted.
Proof of Correctness
By definition, column \(j\) “can be used as a route” if and only if every cell in column \(j\) is sea (.). The algorithm inspects all \(H\) cells of each column \(j\) and sets ok = false whenever at least one # exists. Therefore ok remains true exactly when all cells of the column are ., i.e., exactly for the columns that satisfy the definition. Conversely, a column that can be used as a route contains no #, so ok stays true. Hence the set of columns counted by the algorithm coincides exactly with the set of route-capable columns, and the printed count is correct.
Complexity
- Time: \(O(HW)\) — each cell is examined at most once.
- Space: \(O(1)\) auxiliary space excluding the input storage (\(O(HW)\) for the input strings).
Since \(H, W \leq 10\), any reasonable implementation is easily fast enough.
posted:
last update: