# LeetCode Word Search

LeetCode 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 {
private:
bool dfs(vector<vector<char>>& board, vector<vector<char>>& mark, int row, int col, string& word, int step) {
if (board[row][col] != word[step])return false;
if (step == word.size() - 1)return true;
mark[row][col] = 1;
if (row - 1 >= 0 && mark[row - 1][col] == 0) {
bool ans = dfs(board, mark, row - 1, col, word, step + 1);
if (ans)return true;
}
if (row + 1 < board.size() && mark[row + 1][col] == 0) {
bool ans = dfs(board, mark, row + 1, col, word, step + 1);
if (ans)return true;
}
if (col - 1 >= 0 && mark[row][col - 1] == 0) {
bool ans = dfs(board, mark, row, col - 1, word, step + 1);
if (ans)return true;
}
if (col + 1 <board[0].size() && mark[row][col + 1] == 0) {
bool ans = dfs(board, mark, row, col + 1, word, step + 1);
if (ans)return true;
}
mark[row][col] = 0;
return false;
}

public:
bool exist(vector<vector<char>>& board, string word) {
if (word.size() == 0)return true;
int m = board.size();
if (m == 0)return false;
int n = board[0].size();
if (n == 0)return false;
vector<vector<char>> mark(m, vector<char>(n, 0));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == word[0] && dfs(board, mark, i, j, word, 0))return true;
}
}
return false;
}
};
```

## One thought on “LeetCode Word Search”

1. Pingback: LeetCode Word Search | nce3xin_code