Amazon interview question

Island matrix question in leetcode