Special Island Perimeters
In surveying and resource management applications, accurately calculating land area and perimeters is crucial. Imagine a scenario where you're analyzing geographical data represented as a grid, where different cell types signify water, normal land, or 'special' resource-rich land. These special land areas, while connected to normal land, might have unique properties that affect their perimeter contribution, perhaps due to environmental sensitivities or higher-value resources.
Your task is to implement a system that can precisely measure the total perimeter of all 'islands' in such a grid, taking into account these special land types and their unique perimeter contributions.
Implement the function calculateSpecialIslandPerimeters that takes a 2D grid of integers and returns the total perimeter of all islands within it. An island is formed by connected 1s (normal land) and 2s (special land) in horizontal or vertical directions.
Your function must adhere to the following rules:
1 or 2) are connected if they are horizontally or vertically adjacent.0) or are at the grid boundary.1) contributes 1 unit to the perimeter for each adjacent water cell (0) or grid boundary.2) contributes 2 units to the perimeter for each adjacent water cell (0) or grid boundary.Input:
grid: A number[][] representing the map. Each cell contains 0 (water), 1 (normal land), or 2 (special land).Output:
number representing the total perimeter of all islands in the grid.0).grid is empty or has empty rows, the total perimeter is 0.Examples
Example 1
Input:
grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0]]
Output:
12
Note:
This grid forms a single island. Each '1' cell contributes 1 unit for each adjacent water cell (0) or grid boundary.
Example 2
Input:
grid = [[0,1,0,0],[1,2,1,0],[0,1,0,0]]
Output:
12
Note:
This is similar to the first example but with a '2' cell at (1,1).
Example 3
Input:
grid = [[1,0,0,1],[0,0,0,0],[1,0,2,0]]
Output:
20
Note:
This grid has four separate islands:
Constraints
1 <= grid.length, grid[0].length <= 100grid[i][j] will be 0, 1, or 2.grid[i].length is consistent for all i).1 and 2 cells.Loading editor...