Number of enclaves

Graphs Traversal Problems Medium
  • Fun Fact: Problems like these have practical use in video game development, specifically in world-building and environment design
  • The algorithm that checks for land cells in a grid that you can't walk off is extensively used in designing the navigatable areas in different game maps
  • For instance, popular sandbox games such as Minecraft, where players can manipulate the in-game environment, this checks ensure that there are no inaccessible or infinitely looping paths formed when the players alter the game terrain

Given an N x M binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Find the number of land cells in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Examples:

Input: grid = [[0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]

Output: 3

Explanation:

The highlighted cells represents the land cells.

Input: grid = [[0, 0, 0, 1],[0, 0, 0, 1], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0]]

Output:3

Explanation:

The highlighted cells represents the land cells.

Input: grid = [[0, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]

Constraints

  •   1 <= N, M <= 500
  •   grid[i][j] == 0 or 1

Hints

  • "The binary matrix represents an implicit graph, where each land cell is a node. Water cells (0) act as barriers, preventing movement. Boundary-connected land cells (1s) are not enclosed, so we must exclude them."
  • "Use a visited array to track explored land cells. Alternatively, modify the grid in-place by converting boundary-connected land (1s) to -1 or some marker."

Company Tags

Morgan Stanley Ubisoft Pinterest Salesforce Oracle Target Byju's OYO Rooms Siemens Healthineers Walmart Nutanix Philips Healthcare Splunk Zoho Johnson & Johnson Cerner Stripe MongoDB eBay Qualcomm Flipkart Square KPMG Wayfair Dropbox Google Microsoft Amazon Meta Apple Netflix Adobe