VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-number-of-x-total-shapes/

⇱ Find the number of 'X' total shapes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the number of 'X' total shapes

Last Updated : 23 Jul, 2025

Given a grid of size N * M consisting of O's and X's. The task is to find the number of 'X' total shapes.

Note: 'X' shape consists of one or more adjacents X's (diagonals not included).

Examples:

Input: grid = {{X, O, X}, {O, X, O}, {X, X, X}}
Output: 3
Explanation: The grid is:
X O X   |   X O X   |  X O
O X O  |   O X O   |  O X O
X X X   |   X X X    |  X X X
So, X with bold color are adjacent to each other vertically for horizontally (diagonals not included). So, there are 3 different groups in the given grid.

Input: grid = {{X, X}, {X, X}}
Output: 1
Explanation: The grid is: 
X X
X X
So, X with bold color are adjacent to each other vertically for horizontally (diagonals not included). So, there is only 1 group in the given grid.

Approach: To solve the problem follow the below idea:

The idea is to apply dfs from every cell having 'X' and not visited, mark all its adjacent cells visited if their value is X and increase the answer by one.

Follow the steps to solve this problem:

  • Instead of using an extra vector vis of size n*m to keep track of what cell is visited and not, we can simply convert a visited cell having 'X' to 'O'
  • Initialize variable ans with 0, it will keep count of connected components having only 'X'.
  • Make a function dfs(x, y) to mark the whole connected component having only 'X' as visited by converting all 'X' to 'O'.
  • Run 2 nested loops for iterating over the whole grid
    • Check if the current cell is having 'X', then run a dfs from it and convert all cells in its connected component as 'O' and
    • Increase the variable ans by 1.
  • Return variable ans as the answer.

Below is the implementation of the above approach:


Output
3

Time Complexity: O(N * M), as the vector grid is having N * M cells, and each cell is visited at a max of one time.
Auxiliary Space: O(1) If the recursion stack is considered the time complexity is O(N * M)

Related Articles:

Comment