B - 海図の航路 / Sea Chart Lanes Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
For each column, check whether all cells from top to bottom are sea .. The number of columns that satisfy this condition is the answer.
Analysis
Since the ship moves straight along the chosen column, it cannot be used as a route if there is even a single cell of island # in that column. Conversely, if all cells are ., that column can be used as a route.
For example, consider the following sea chart:
..#.
.#..
....
- 1st column: All cells are
., so it can be used as a route. - 2nd column: It contains
#, so it cannot be used as a route. - 3rd column: It contains
#, so it cannot be used as a route. - 4th column: All cells are
., so it can be used as a route.
Therefore, the answer is \(2\).
In this problem, since \(H, W \leq 10\), a naive approach that checks all cells easily runs within the time limit. No optimization is necessary.
However, counting the total number of sea cells or checking horizontal rows will not give the correct answer. It is essential to determine whether all cells in that column are sea, column by column.
Algorithm
- Read the sea chart as a list of strings
S. - Initialize the number of usable columns
ansto \(0\). - For each column \(j = 0, 1, \ldots, W-1\), perform the following:
- Check if
S[i][j]is.for all rows \(i = 0, 1, \ldots, H-1\). - If all are
., incrementansby \(1\).
- Check if
- Output
ans.
Since we directly verify the route condition “all cells are sea” for each column and count each qualifying column exactly once, this yields the correct answer.
Complexity
- Time complexity: \(O(HW)\)
For each of the \(W\) columns, at most \(H\) cells are checked. - Space complexity: \(O(HW)\)
Required to store the sea chart. The auxiliary space complexity excluding the input storage is \(O(1)\).
Implementation Notes
- Python uses \(0\)-based indexing.
S[i][j]represents the cell at the \((i+1)\)-th row from the top and the \((j+1)\)-th column from the left. - The outer loop iterates over the columns, and the inner loop checks each row in that column.
- In the code, whether “all cells in the column are sea” is determined using the following expression:
all(S[i][j] == '.' for i in range(H))
all() returns True if and only if all given conditions are true. If a # is encountered along the way, it immediately returns False.
Source Code
import sys
def main():
data = sys.stdin.read().split()
H = int(data[0])
W = int(data[1])
S = data[2:2 + H]
ans = 0
for j in range(W):
if all(S[i][j] == '.' for i in range(H)):
ans += 1
print(ans)
main()
This editorial was generated by gpt-6-astra-medium.
posted:
last update: