# Word Search

Given a 2D board and a word, find if the word exists in the grid.

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

For example,

Given board =

```
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
```

word = "ABCCED", -> returns true,

word = "SEE", -> returns true,

word = "ABCB", -> returns false.

```
class Solution {
func exist(_ board: [[Character]], _ word: String) -> Bool {
if board.isEmpty || board[0].isEmpty || word.isEmpty {
return false
}
var visited: [[Bool]] = Array(repeating: Array(repeating: false,
count: board[0].count), count: board.count)
for i in 0..<board.count {
for j in 0..<board[0].count {
if dfs(board, word, i, j, 0, &visited) {
return true
}
}
}
return false
}
func dfs(_ board: [[Character]], _ word: String, _ i: Int, _ j: Int, _ index: Int,
_ visited: inout [[Bool]]) -> Bool {
if index == word.count {
return true
}
if i < 0 || i > board.count - 1 || j < 0 || j > board[i].count - 1 {
return false
}
if visited[i][j] {
return false
}
if board[i][j] != word[word.index(word.startIndex, offsetBy: index)] {
return false
}
visited[i][j] = true
var exists: Bool = dfs(board, word, i + 1, j, index + 1, &visited)
|| dfs(board, word, i - 1, j, index + 1, &visited)
|| dfs(board, word, i, j + 1, index + 1, &visited)
|| dfs(board, word, i, j - 1, index + 1, &visited)
visited[i][j] = false
return exists
}
}
```

```
public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
int m = board.length, n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dfs(board, word, 0, i, j, visited)) {
return true;
}
}
}
return false;
}
boolean dfs(char[][] board, String word, int index, int i, int j,
boolean[][] visited) {
if (index == word.length()) {
return true;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return false;
}
if (visited[i][j]) {
return false;
}
if (word.charAt(index) != board[i][j]) {
return false;
}
visited[i][j] = true;
index = index + 1;
boolean result = dfs(board, word, index, i, j + 1, visited)
|| dfs(board, word, index, i, j - 1, visited)
|| dfs(board, word, index, i + 1, j, visited)
|| dfs(board, word, index, i - 1, j, visited);
visited[i][j] = false;
return result;
}
}
```

Hope this helps,

Michael