Ctrl K

Same-Letter Loop in a Grid

Medium
You are given an m × n grid board with a lowercase English letter in every cell. From a cell you may step to a side neighbour (up, down, left or right) only if it holds the same letter. A loop is a walk of 4 or more steps that starts and ends at the same cell, where you may never step straight back into the cell you just came from (going there and back does not count as a loop). Return True if the grid contains at least one loop of matching letters, and False otherwise.
Example 1
board=[['x', 'x', 'y'], ['x', 'x', 'y'], ['z', 'y', 'y']] → True

The four x cells in the top-left corner form a 2×2 square, which is a loop of length 4.

Example 2
board=[['a', 'b', 'a'], ['a', 'a', 'a'], ['b', 'a', 'b']] → False

The a cells are connected, but they branch like a tree: there is no way back to the start without stepping straight back.

Example 3
board=[['p', 'p', 'p'], ['p', 'q', 'p'], ['p', 'p', 'p']] → True

The p cells run in a ring around the q in the middle.

Constraints
  • 1 ≤ m, n ≤ 500
  • All rows of board have the same length
  • board[i][j] is a lowercase English letter
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDrain the Landlocked Ponds MediumLand Regions on a Map MediumLargest Forest Patch MediumA Board Cut by Slashes MediumLandlocked Land Cells Medium
loading Python…
Input
board=[['x', 'x', 'y'], ['x', 'x', 'y'], ['z', 'y', 'y']]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 77 tests on the server, hidden ones included.