![]() |
VOOZH | about |
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 X
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:
Below is the implementation of the above approach:
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: