Getting tle error

what is the optimum way to do this question

@sreejan123
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.

https://ide.codingblocks.com/s/317592 please check the code i used dp in this

refer to this