oneby7

Graphs Grids as graphs

439. Number of Distinct Islands

Medium

You are given a map as a grid of integers, grid, with m rows and n columns. A cell that holds 1 is land, and a cell that holds 0 is water.

An island is a group of land cells joined by steps up, down, left or right. Two land cells that touch only at a corner are not joined. Everything outside the grid is water.

Two islands have the same shape when one can slide onto the other, without turning or flipping, so that its land cells cover the other's land cells exactly. Return the number of different shapes among the islands in grid.

Example 1

110011100010001000011011000010

Input: grid = [[1, 1, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1], [0, 0, 0, 0, 1, 0]]

Output: 2

Explanation: There are four islands of three cells. The two at the top and the one at the bottom right have the same shape, since each can slide onto the others. The island in the middle is that shape turned around, and turning is not allowed, so it is a second shape.

Example 2

101010101

Input: grid = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]

Output: 1

Explanation: The five land cells touch only at corners, so each one is an island of a single cell. They all have the same shape.

Example 3

1101110001

Input: grid = [[1, 1, 0, 1, 1], [1, 0, 0, 0, 1]]

Output: 2

Explanation: Each island is the mirror image of the other. Flipping is not allowed, so no slide puts one onto the other.

Check your understanding

Work out the answer for this input before you write any code.

grid = [[1, 1, 0, 1], [0, 0, 0, 1], [1, 0, 1, 0], [1, 0, 1, 0]]

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 300
  • grid[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.