Skip to content
Problem 764 · LeetCode 764(opens in a new tab)

Largest Plus Sign

MediumDynamic programming

Picture an n × n grid filled with 1s, except for a few cells listed in mines, which hold 0. Each entry of mines is a pair [row, column].

A plus sign of order k is a centre cell of 1 with four arms going up, down, left and right, each made of k − 1 more cells of 1. So order 1 is a single cell. Only the centre and the arms must be 1; the cells around them do not matter. Return the largest order of any plus sign in the grid, or 0 if every cell is a mine.

Example 1

Input:  n = 5, mines = [[1, 2], [2, 4], [3, 0]]
Output: 2
Why:    centre (2, 1) with arms of length 1; no order-3 plus fits
2 more examples and the constraints

Example 2

Input:  n = 2, mines = [[0, 1]]
Output: 1
Why:    a 2 × 2 grid is too small for arms, but open cells remain

Example 3

Input:  n = 3, mines = [[0, 0]]
Output: 2
Why:    the centre (1, 1) and its four neighbours are all open

Constraints

  • 1 ≤ n ≤ 500
  • 1 ≤ number of mines ≤ 5,000
  • Every mine is inside the grid, and no mine is listed twice

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Grow a plus from every cellO(n³)
  2. Four direction sweepsO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 500Verdict
Grow a plus from every cellO(n³)
Correct; repeats walks
Four direction sweepsO(n²)
Best; each cell 4 times

n = side length of the grid; m = number of mines.

Edge cases to test

  • Every cell a mine. n = 1 with mine [0, 0] gives 0.
  • Grid too small for arms. n = 2 gives at most 1, whatever the mines.
  • Mines only in a corner. n = 3 with mine [0, 0] still fits an order-2 plus in the middle.
  • Large grid, one mine. n = 300 with a mine at [0, 0] gives 150: the arms stop at the edges.
  • A mine at the centre. It caps every run through it, so the best plus moves elsewhere.

Common mistakes

  • Counting arm length instead of order: a single open cell is order 1, not 0.
  • Resetting the run to 1 instead of 0 on a mine, so a mine looks like an open cell.
  • Sweeping only one direction per row or column, which ignores the arm on the other side.

How to talk through it

  1. 1Clarify. Does order 1 mean one cell? Do the cells beside the arms matter? Can every cell be a mine?
  2. 2Give the brute force. Grow a plus from every centre: O(n³), too slow for n = 500.
  3. 3Name the four runs. A plus is limited by its shortest run of open cells in the four directions.
  4. 4Code the sweeps. Start at n, sweep each line both ways, keep a running count, take the min.
  5. 5Test out loud. Run the all-mines grid and a 2 × 2 grid before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?