Difficulty | Source | Tags | ||||
---|---|---|---|---|---|---|
Medium |
160 Days of Problem Solving |
|
The problem can be found at the following link: Problem Link
You are given a two-dimensional mat[][]
of size n × m
containing English alphabets and a string word
.
Check if the word
exists in the mat
. The word can be constructed by using letters from adjacent cells,
either horizontally or vertically. The same cell cannot be used more than once.
Input:
mat[][] = [['T', 'E', 'E'],
['S', 'G', 'K'],
['T', 'E', 'L']]
word = "GEEK"
Output:
true
Explanation:
![](https://private-user-images.githubusercontent.com/124852522/408774768-93e597c2-f34a-418c-b5bf-9a945371ac55.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3Mzg5OTYyMzksIm5iZiI6MTczODk5NTkzOSwicGF0aCI6Ii8xMjQ4NTI1MjIvNDA4Nzc0NzY4LTkzZTU5N2MyLWYzNGEtNDE4Yy1iNWJmLTlhOTQ1MzcxYWM1NS5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMjA4JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDIwOFQwNjI1MzlaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT00NmI2ZjAxZjAzOGExMTRjNTc1ODAzODFlNTA4MGY1MzliYmU2OTVjZjdmZGZkZjU1MWY0ZjE0MTM4M2U2ZGVlJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.aT_5erlTOpLy49yEQQAxhREJkOYV8dywqr9TZT45vik)
The letters used to construct "GEEK" are found in the grid.
Input:
mat[][] = [['T', 'E', 'U'],
['S', 'G', 'K'],
['T', 'E', 'L']]
word = "GEEK"
Output:
false
Explanation:
![](https://private-user-images.githubusercontent.com/124852522/408774787-c90d723f-a1bd-4483-ba9d-e5903684b481.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3Mzg5OTYyMzksIm5iZiI6MTczODk5NTkzOSwicGF0aCI6Ii8xMjQ4NTI1MjIvNDA4Nzc0Nzg3LWM5MGQ3MjNmLWExYmQtNDQ4My1iYTlkLWU1OTAzNjg0YjQ4MS5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMjA4JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDIwOFQwNjI1MzlaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1lYWM0YzYwMjk0ZTdjZDdhY2ExMzU3YWQzNDE1Mjc2ZDcxMTVjYzRmMWYyOWY3YjNlYTVmMDY0MTkxNGMxZDBhJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.kHbXHTH5UmyY0G8hxy2bF6Oydecv2y_K-S7XIlMAUcE)
The word "GEEK" cannot be formed from the given grid.
Input:
mat[][] = [['A', 'B', 'A'],
['B', 'A', 'B']]
word = "AB"
Output:
true
Explanation:
![](https://private-user-images.githubusercontent.com/124852522/408774796-f8d9c68d-6447-4817-8646-7c1a1497ac5e.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3Mzg5OTYyMzksIm5iZiI6MTczODk5NTkzOSwicGF0aCI6Ii8xMjQ4NTI1MjIvNDA4Nzc0Nzk2LWY4ZDljNjhkLTY0NDctNDgxNy04NjQ2LTdjMWExNDk3YWM1ZS5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMjA4JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDIwOFQwNjI1MzlaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT01MWEwN2NkNTA5M2JiY2U5YTVmZjg4MWYzNTRkNWFlZGZhNmY4ZjhlZmNjNjAxMzVjODY5MzJkMjI2ZDFjNTQ1JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.p4T-hnvCv8AX2A4dE-P1e7ZCIH5G6n3wPA9pIYvq0fk)
There are multiple ways to construct the word "AB".
1 ≤ n, m ≤ 100
1 ≤ L ≤ n * m
(whereL
is the length of the word)
-
Start from Each Cell
- Iterate over the matrix to find the first letter of the word.
- If a match is found, perform DFS from that position.
-
Recursive DFS Traversal
- Check the four possible directions: up, down, left, right.
- If the next character in the word is found, move to that cell.
- Temporarily mark the cell as visited (
'#'
) to prevent reusing it in the same search path.
-
Backtracking
- Restore the cell's original value after exploring all paths from that cell.
- If the complete word is found, return
true
.
-
Optimization
- If the first letter of
word
is not found inmat[][]
, returnfalse
immediately. - Stop searching as soon as the word is found.
- If the first letter of
-
Expected Time Complexity:
O(n * m * 4^L)
, wheren × m
is the size of the matrix andL
is the length of the word.- We perform DFS from every cell (
O(n * m)
). - Each DFS call explores up to 4 directions, leading to a worst-case exponential growth (
O(4^L)
).
- We perform DFS from every cell (
-
Expected Auxiliary Space Complexity:
O(L)
, due to the recursive call stack of depth L (length of the word).- We modify the grid temporarily (
O(n * m)
) but revert it back (constant space usage).
- We modify the grid temporarily (
class Solution {
public:
bool dfs(vector<vector<char>> &b, string &w, int i, int j, int k) {
if(k == w.size()) return true;
if(i < 0 || j < 0 || i >= b.size() || j >= b[0].size() || b[i][j] != w[k]) return false;
char t = b[i][j];
b[i][j] = '#';
bool f = dfs(b, w, i-1, j, k+1) || dfs(b, w, i+1, j, k+1) ||
dfs(b, w, i, j-1, k+1) || dfs(b, w, i, j+1, k+1);
b[i][j] = t;
return f;
}
bool isWordExist(vector<vector<char>> &b, string w) {
for(int i = 0; i < b.size(); i++)
for(int j = 0; j < b[0].size(); j++)
if(b[i][j] == w[0] && dfs(b, w, i, j, 0))
return true;
return false;
}
};
class Solution {
public boolean isWordExist(char[][] b, String w) {
for (int i = 0; i < b.length; i++)
for (int j = 0; j < b[0].length; j++)
if (b[i][j] == w.charAt(0) && dfs(b, w, i, j, 0))
return true;
return false;
}
private boolean dfs(char[][] b, String w, int i, int j, int k) {
if (k == w.length()) return true;
if (i < 0 || j < 0 || i >= b.length || j >= b[0].length || b[i][j] != w.charAt(k)) return false;
char t = b[i][j];
b[i][j] = '#';
boolean f = dfs(b, w, i - 1, j, k + 1) || dfs(b, w, i + 1, j, k + 1) ||
dfs(b, w, i, j - 1, k + 1) || dfs(b, w, i, j + 1, k + 1);
b[i][j] = t;
return f;
}
}
class Solution:
def isWordExist(self, b, w):
def dfs(i, j, k):
if k == len(w): return True
if i < 0 or j < 0 or i >= len(b) or j >= len(b[0]) or b[i][j] != w[k]: return False
t, b[i][j] = b[i][j], '#'
f = any(dfs(i + dx, j + dy, k + 1) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)])
b[i][j] = t
return f
return any(dfs(i, j, 0) for i in range(len(b)) for j in range(len(b[0])) if b[i][j] == w[0])
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐