I suggest adding the following to the Solution class:
bool DFS(int r, int c, int from_r, int from_c); |
Here's the pseudo-code of the DFS:
bool DFS(int r, int c, int from_r, int from_c)
{
if (V[r][c] shows that we're in the DFS already from r and c, return true, because we just detected a cycle.
if (V[r][c] shows that we've already processed r and c, return false.
set V[r][c] to show that we're in the DFS from r and c
for each of the four legal directions from r and c:
if (there is a node in that direction, and
that node's character matches the character in r and c, and
that node is not (from_r,from_c)) then
do the DFS to that node.
If it returns true, we're done and we found a cycle -- return true.
If it returns false, keep going.
If we get here, then there is no cycle involving r and c, so:
set V[r][c] to show that we already processed r and c
return false
}
|
It's good practice for you to write this.
If you read the problem editorial, you'll see that you can also solve this with disjoint sets, and it's faster. That's all well and good, but I think it's good practice for you to write the DFS.