Official

D - Weak Takahashi Editorial by en_translator


Let \(f(i, j)\) the maximum number of squares he can visit before he stops if he starts walking from square \((i, j)\).

For convenience, let \(f(i, j) = 0\) if \((i, j)\) is a wall or outside the grid. Then, for any empty square \((i, j)\), the following relation holds.

  • \(f(i, j) = \max (f(i + 1, j), f(i, j + 1)) + 1\)

Therefore, one can determine \(f(i, j)\) in order, larger indices first. The answer is \(f(1, 1)\).

Note that the problem statements and this editorial are 1-indexed, while the sample code below is 0-indexed.
Sample code (C++):

#include <bits/stdc++.h>
using namespace std;

int main() {
  int n, m;
  cin >> n >> m;
  vector c(n, vector<char>(m));
  for (auto& v : c) {
    for (char& x : v) {
      cin >> x;
    }
  }
  vector f(n + 1, vector<int>(m + 1));
  for (int i = n - 1; i >= 0; --i) {
    for (int j = m - 1; j >= 0; --j) {
      if (c[i][j] == '#') continue;
      f[i][j] = max(f[i + 1][j], f[i][j + 1]) + 1;
    }
  }
  cout << f[0][0] << '\n';
}

posted:
last update: