How to optimize this problem

how to optimize this problem expand the pond

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.