Amazon Interview Question

Island matrix question in leetcode