23. Find the string in grid
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
I have used a straightforward approach to solve this problem.
Start iterating through each cell in the grid
.
For each cell, I check if the first character of the word matches the character in the current cell.
If it does, I explore in all eight possible directions (up, down, left, right, and diagonally)
to see if the entire word can be formed.
To do this, I use the canForm
function that checks if the word can be formed starting from the current cell in a given direction.
If I find a match, I add the starting cell's coordinates to the out
vector.
I continue this process until I have searched the entire grid.
Time Complexity: The code iterates through each cell in the grid exactly once, and for each cell, it explores eight possible directions to check if the word can be formed. So, the time complexity is O(N * M * 8 * W)
, where N
is the number of rows in the grid, M
is the number of columns, and W
is the length of the target word.
Auxiliary Space Complexity: The auxiliary space used is minimal. The out
vector stores the starting positions of the target word, which can be at most the size of the grid, so the space complexity is O(N * M)
.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.