Define grid[r][c] to be the integer in the -th row of the -th column of
the input grid. Let done[x]=true if we can reach any cell such that
and false otherwise. If done[x] is true, then we also know
that done[grid[r][c]] is true for all cells such that .
So we essentially have a directed graph with vertices where there
exists a directed edge from x to grid[r][c] whenever . We want
to test whether there exists a path from to in this graph.
Thus, we can simply start DFSing from vertex and mark all the vertices that
we visit in the boolean array done. If we set done[N*M]=true, then a path
exists, and we can terminate after printing "yes." Note that in the code below,
todo[x] denotes the adjacency list of x.
#include <bits/stdc++.h>using namespace std;int M, N;vector<int> todo[1000005];bool done[1000005];void dfs(int x) {if (done[x]) { return; }
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!