BackmediumRecursion Uber

Galactic Colony Border Calculator Solution

Problem Statement

In a 2D grid representing a galaxy, where 0 indicates empty space and 1 indicates a colonized planet, calculate the total border length of all colonies, considering each cell as a planet with a border length of 1 unit, and only counting borders that are adjacent to empty space or the edge of the grid.

Example 1
Input
[[1,0,1],[0,1,0],[1,0,1]]
Output
14

Explanation: Step-by-step: Given a 3x3 grid with planets at (0,0), (0,2), (2,0), and (2,2), we calculate the border length of each planet. The planet at (0,0) has 3 adjacent empty spaces, the planet at (0,2) has 3 adjacent empty spaces, the planet at (2,0) has 3 adjacent empty spaces, and the planet at (2,2) has 3 adjacent empty spaces. The remaining planets have 2 adjacent empty spaces each. Therefore, the total border length is 3 + 3 + 3 + 3 + 2 + 2 + 2 + 2 = 14.

Example 2
Input
[[1,0,1,0],[0,1,0,0],[1,0,1,1],[0,0,0,1]]
Output
10

Explanation: Step-by-step: Given a 4x4 grid with planets at (0,0), (0,2), (2,0), and (2,2), we calculate the border length of each planet. The planet at (0,0) has 3 adjacent empty spaces, the planet at (0,2) has 3 adjacent empty spaces, the planet at (2,0) has 3 adjacent empty spaces, and the planet at (2,2) has 3 adjacent empty spaces. The remaining planets have 2 adjacent empty spaces each. Therefore, the total border length is 3 + 3 + 3 + 3 + 2 + 2 = 10.

Constraints

  • The input grid size will be between 1x1 and 50x50.
  • The grid will only contain 0s (empty space) and 1s (colonized planets).
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free