Go to the adjacent cells
for i in range ( 4 ) : NEW_LINE INDENT newX = x + dx [ i ] NEW_LINE newY = y + dy [ i ] NEW_LINE if ( is_valid ( newX , newY , matrix ) ) : NEW_LINE INDENT q . append ( [ newX , newY ] ) NEW_LINE visited [ newX ] [ newY ] = True NEW_LINE DEDENT DEDENT if COUNT in mp : NEW_LINE mp [ COUNT ] += 1 NEW_LINE else : NEW_LINE mp [ COUNT ] = 1 NEW_LINE