Explain the solution

i am getting tle , please explain a better approach
\

@vinishthanai
keep a count of visited array and keep marking all the nodes once visited, so that you dont visit them again, secodly mark all the connected componenets with an index , finaly just take five distinct values of every index , up,down,left,right,and that index it self.