# Word Search

Medium

Given an m x n `board` and a `word`, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where “adjacent” cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

```Input: board = [["A","B","C","E"],
["S","F","C","S"],
["A","D","E","E"]],
word = "ABCCED"

Output: true```

Example 2:

```Input: board = [["A","B","C","E"],
["S","F","C","S"],
["A","D","E","E"]],
word = "SEE"
Output: true```

Constraints:

• `m == board.length`
• `n = board[i].length`
• `1 <= m, n <= 200`
• `1 <= word.length <= 103`
• `board` and `word` consists only of lowercase and uppercase English letters.

Implementation

```class Solution {

private boolean[][] visited = null;

public boolean exist(char[][] board, String word) {

if(board == null || board.length == 0 || board.length == 0){
return false;
}
int m = board.length;
int n = board.length;
this.visited = new boolean[m][n];

for(int i = 0 ; i < m ; i++){
for(int j = 0 ; j < n ; j++){
if(board[i][j] == word.charAt(0) && canFormWord(board, i, j, m, n, word, 0)){
return true;
}
}
}
return false;
}

private boolean canFormWord(char[][] board, int i, int j, int m, int n, String word, int len){

if(len == word.length()){
return true;
}
if( i < 0 || i == m || j < 0 || j == n || visited[i][j] || board[i][j] != word.charAt(len)){
return false;
}
visited[i][j] = true;
if(canFormWord(board, i+1, j, m, n, word, len+1) || canFormWord(board, i-1, j, m, n, word, len+1) ||
canFormWord(board, i, j+ 1, m, n, word, len+1)|| canFormWord(board, i, j-1, m, n, word, len+1)){
return true;
}
visited[i][j] = false;
return false;
}
}
```

Time Complexcity: `O(M*N*4L)`, where `L` is the length of the word.

Categories: 2D Array, DFS

Tagged as: ,