[LeetCode] Word Search

79. Word Search

Given an m x n grid of characters board and a string word, return true if 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
int n, m, len;
int dx[4] {0, 1, 0, -1};
int dy[4] {-1, 0, 1, 0};
bool v[6][6] = {false, };
bool chk(int y, int x, vector<vector<char>>& board, string& word, int pos) {
if(pos == len) return true;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if(0 <= nx && nx < m && 0 <= ny && ny < n && !v[ny][nx] && board[ny][nx] == word[pos]) {
v[ny][nx] = true;
if(chk(ny, nx, board, word, pos + 1)) return true;
v[ny][nx] = false;
}
}
return false;

}
public:
bool exist(vector<vector<char>>& board, string word) {
n = board.size(), m = board[0].size(), len = word.length();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
v[i][j] = true;
if(board[i][j] == word[0] && chk(i, j, board, word, 1)) return true;
v[i][j] = false;
}
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/29/PS/LeetCode/word-search/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.