Flatten the grid into a single string (separated by line-feeds to side-step wrap-around problems) and use the offset in the string to identify cells instead of (x, y) tuples. Don't calculate part one separately, just do it as we go.
No point checking for connected nodes in +x or +y directions, as we haven't processed them yet.