2025 Coding Team Tryouts P3 - Triangular Manhattan Perimeter


Submit solution

Points: 6 (partial)
Time limit: 1.0s
Memory limit: 256M

Author:
Problem type

As an early (or late) birthday present, Pythogoras gives you an \(N \times N\) grid (\(2 \le N \le 1000\)).
Each cell in the grid contains a \(0\) except for exactly three of them, which contain \(1\)'s. These three \(1\)'s collectively form a triangle.

Alongside his gift, Pythogoras presents you the challenge: calculate the perimeter of the triangle.
But there's a catch. Instead of calculating using Euclidean distance, you are asked to calculate the perimeter using Manhattan distance.

Specifically, the Manhattan distance between two points (\(r_1\), \(c_1\)) and (\(r_2\), \(c_2\)) is \(|r_1-r_2|+|c_1-c_2|\).
For example, the Manhattan distance between \((2, 4)\) and \((3, 1)\) is \(|2-3|+|4-1|=4\).

Input Specification

The first line contains the integer \(N\).
The next \(N\) lines each contain \(N\) space-separated characters (either \(0\) or \(1\)).
It is guaranteed there will be exactly three \(1\)'s total.

Output Specification

Calculating using Manhattan distance, what is the perimeter of the triangle?

Sample Input

3
0 1 0
0 0 1
1 0 0

Sample Output

8

If we treat the top left corner as \((1,1)\) and the bottom right corner as \((3,3)\), we get the following points: \((1, 2)\), \((2, 3)\), and \((3, 1)\) for the cells with \(1\)'s. We can calculate the perimeter as follows:
\((|1-2|+|2-3|)+(|1-3|+|2-1|)+(|2-3|+|3-1|)=8\)


Comments

There are no comments at the moment.