How to count groups of same cells in a 2d array?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Counting groups of equal cells in a 2D grid is a connected-components problem. The standard solution is to scan the grid and start a traversal such as depth-first search or breadth-first search whenever you find an unvisited cell, marking every connected cell of the same value as part of that group.
Define What Counts as a Group
Before writing code, decide the adjacency rule. Two common choices are:
- four-directional adjacency: up, down, left, right
- eight-directional adjacency: the four directions above plus diagonals
The group count can change depending on that definition, so the algorithm must encode the same rule the problem expects.
For example, in four-directional mode, diagonal neighbors do not belong to the same group unless there is a path through side-adjacent cells.
DFS Approach
A depth-first search is often the simplest implementation. When you find an unvisited cell, you start a DFS that visits all same-valued connected neighbors. That whole traversal counts as one group.
This counts connected regions by value under four-directional adjacency.
BFS Works Too
Breadth-first search solves the same problem with a queue instead of recursion. That can be useful if you want to avoid recursion-depth issues on large grids.
The overall counting loop stays the same. Only the traversal mechanism changes.
Complexity
Each cell is visited once, so the time complexity is O(rows * cols). The visited matrix also costs O(rows * cols) space, and DFS or BFS needs additional stack or queue space proportional to the size of a component.
That is already optimal for this style of full-grid traversal because every cell must be examined at least once.
Common Pitfalls
- Failing to define whether adjacency is four-directional or eight-directional changes the answer. Match the traversal rule to the problem statement exactly.
- Forgetting a visited structure causes repeated work or infinite recursion as the search revisits the same cells. Mark cells as soon as they are discovered.
- Counting every equal value instead of every connected region solves a different problem. Groups depend on connectivity, not only on value frequency.
- Using recursive DFS on a very large grid can hit recursion limits in Python. Switch to BFS or an explicit stack if the input may be large.
- Starting a new traversal before checking
visitedinflates the group count. Only launch DFS or BFS from cells that have not already been assigned to a group.
Summary
- Counting same-valued groups in a 2D array is a connected-components problem.
- Scan the grid and run DFS or BFS from each unvisited cell.
- Mark all connected cells with the same value during that traversal.
- The result depends on whether adjacency is four-directional or eight-directional.
- A correct solution visits each cell once, so the time complexity is linear in the number of cells.
Related reading
- How to count integers between large A and B with a certain property?
- How to count Multiply-Adds operations?
- How to count string num with limit memory?
- How to count the frequency of the elements in an unordered list?
- How to count occurrences of an element in a Swift array?
- How to count the number of occurrences of an element in a List
- How to create a distributed system that performs a task and come to a consensus of result?
- How to create a good evaluation function for a game?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.