Official

B - 海図の航路 / Sea Chart Lanes Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

For each column, we check if all cells are sea (.). The number of columns that satisfy this condition is the answer.

Analysis

Since the ship travels straight from top to bottom through the chosen column, that column cannot be used as a sailing route if it contains even a single island (#). In other words, the condition for a column to be a valid route is that all cells in the column are ..

For example, consider the following sea chart:

..#.
.#..
....
  • 1st column from the left: All cells are ., so it can be used as a route.
  • 2nd column from the left: Contains #, so it cannot be used as a route.
  • 3rd column from the left: Contains #, so it cannot be used as a route.
  • 4th column from the left: All cells are ., so it can be used as a route.

Therefore, the answer is \(2\).

For this problem, a naive approach of checking all cells in each column is sufficient. Since \(H, W \leq 10\), there are at most \(100\) cells to inspect, so there is no concern about exceeding the time limit.

Note that counting the total number of sea cells or checking row by row will not yield the correct answer. Make sure to inspect by “column”.

Algorithm

  1. Read the sea chart as a list of strings g.
  2. Initialize the answer variable ans to \(0\).
  3. For each column \(j\), check whether g[i][j] is . for all rows \(i\).
    • If all are ., that column can be used as a route, so add \(1\) to ans.
  4. Output ans.

This process correctly finds the answer because each column satisfying the route condition is counted exactly once.

Complexity

  • Time Complexity: \(O(HW)\)
    • For each of the \(W\) columns, at most \(H\) cells are checked.
  • Space Complexity: \(O(HW)\)
    • Stores the entire sea chart. The additional space used besides storing the chart is \(O(1)\).

Implementation Notes

Indices in Python are \(0\)-based. g[i][j] represents the cell in the \((i+1)\)-th row from the top and the \((j+1)\)-th column from the left.

In the code, the following expression is used to check whether all cells in the column are sea:

all(g[i][j] == '.' for i in range(h))

all returns True if all evaluated conditions are true. If a # is found along the way, it returns False immediately, eliminating the need to check the remaining cells.

Source Code

# 問題文から独立に実装: 各列を縦に見て '#' が無ければ数える
h, w = map(int, input().split())
g = [input().strip() for _ in range(h)]
ans = 0
for j in range(w):
    if all(g[i][j] == '.' for i in range(h)):
        ans += 1
print(ans)

This editorial was generated by gpt-6-astra-medium.

posted:
last update: