Skip to content

ORIGINAL CODING QUESTION

Total land border length

Return the number of land-cell sides touching water or outside the grid. Multiple islands and enclosed water are allowed.

Open practice workspace

Original exercise · easy. Editorial role relevance does not imply a company has asked this question.

Input and output

rows cols, then rows×cols cell values in row-major order. Print one integer.

Constraints

1 ≤ rows,cols ≤ 12; each cell is 0 or 1; adjacency uses four sides, not diagonals.

Example 1

Input

1 2 1 1

Output

6

Two adjacent land cells have border length 6.

Example 2

Input

2 2 1 1 1 1

Output

8

The solid square has border 8.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Each land cell contributes four sides initially.

Hint 2

Each land-to-land shared edge removes two sides.

Hint 3

Count shared edges only once, such as to the right and below.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →