You’re given an R-by-C array of integers that represents a top-down map of a building construction site, where each location in the array represents a one-meter by one-meter square of land. In this array, a 0 means that there will be nothing built on that square, and a 1 means that the building will include that square.
Assume that at most one building is planned for the site. Return the perimeter of that building.
Examples:
[[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0]] -> the perimeter of the building is 4.
[[0, 0, 0, 0, 0],
[0, 1, 1, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 0]] -> the perimeter of the building is 8.
[[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]] -> the perimeter of the building is 4.
[[1, 1, 1],
[1, 0, 1],
[1, 1, 1]] -> should return 12. We only count the 12m perimeter on the north/south/east/west, not the extra 4m perimeter that faces the internal courtyard.
[[1, 0, 1],
[1, 0, 1],
[1, 1, 1]] -> should return 14.
This problem asks for the perimeter of a connected building shape in a 2D grid. A clean solution is to scan every cell with value 1, add 4 for its four sides, and subtract 1 for each neighboring land cell that shares an edge. That automatically handles rectangles, irregular shapes, and internal courtyards, because shared borders are not part of the outer perimeter. The approach runs in O(RC) time and is simple to implement in an interview.