Problem 61156. How Long is the Border Between Unitopia and Zerostan?
Two countries, Unitopia (denoted by ones) and Zerostan (denoted by zeros) are engaged in a long-standing dispute: how long is the border between their two domains?
You are the surveyor contracted to resolve this problem once and for all.
The border between the two countries is the sum of all the line segments that separate a 1 from a 0. Only horizontal and vertical adjacencies count (4-connected neighbors). The matrix edges do not count as borders - only internal segments between 1s and 0s.
The input map will be a rectangular matrix of integers. Not all integers will be 1s and 0s, but the border you are interested in is only between 1s and 0s. Other values are ignored and do not contribute to the border length.
In every case, each country will be a 4-connected region. That is, you can make a tour of every element in a given country (all 1s or all 0s) without crossing an international boundary.
Example 1
Single cell surrounded by zeros:
Input:
[0 0 0
0 1 0
0 0 0]
Output: 4
The 1 has four neighbors (up, down, left, right), all are 0s, so border length = 4.
Example 2
Matrix with other values:
Input:
[0 0 0 0
1 1 0 0
2 2 2 2]
Output: 3
Only 1-to-0 adjacencies (shown in red) count. The two 1s touch 0s: right 1 has 2 border segments with 0s, left 1 has 1 border segment. Total = 3. The 2s are ignored.
Solution Stats
Solution Comments
Show commentsProblem Recent Solvers6
Suggested Problems
More from this Author54
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!