Skip to content

Commit 7aa8d5f

Browse files
committed
Feat: solve #255
1 parent 42b40d0 commit 7aa8d5f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

โ€Žword-search/crumbs22.cpp

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <vector>
2+
#include <string>
3+
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
bool exist(vector<vector<char>>& board, string word) {
9+
// ๋‹จ์–ด ์‹œ์ž‘์ ์„ ํƒ์ƒ‰, ์‹œ์ž‘์  ์ฐพ์œผ๋ฉด dfs ์‹œ์ž‘ํ•˜๊ณ  ๋งˆ์ง€๋ง‰ ๋‹จ์–ด๊นŒ์ง€ ๋„๋‹ฌ ๊ฐ€๋Šฅํ•  ๋•Œ true ๋ฐ˜ํ™˜
10+
for (int i = 0; i < board.size(); i++) {
11+
for (int j = 0; j < board[0].size(); j++) {
12+
if (board[i][j] == word[0] && dfs(board, i, j, 0, word)) {
13+
return (true);
14+
}
15+
}
16+
}
17+
return (false);
18+
}
19+
bool dfs(vector<vector<char>>& board, int i, int j, int idx, string& word) {
20+
if (idx == word.size())
21+
return (true);
22+
if (i < 0 || i >= board.size() || \
23+
j < 0 || j >= board[0].size() || \
24+
board[i][j] != word[idx]) {
25+
return (false);
26+
}
27+
28+
char tmp = board[i][j];
29+
30+
// ๋ฐฉ๋ฌธ ํ‘œ์‹œ
31+
board[i][j] = '1';
32+
33+
// 4๋ฐฉํ–ฅ์œผ๋กœ ํƒ์ƒ‰
34+
bool found = dfs(board, i + 1, j, idx + 1, word) || dfs(board, i - 1, j, idx + 1, word) || \
35+
dfs(board, i, j + 1, idx + 1, word) || dfs(board, i, j - 1, idx + 1, word);
36+
37+
// ๋‹ค๋ฅธ ๊ฒฝ๋กœ ํƒ์ƒ‰์„ ์œ„ํ•ด์„œ ๋ฐฉ๋ฌธ ํ‘œ์‹œ๋ฅผ ์›๋ž˜๋Œ€๋กœ ๋ณต์›
38+
board[i][j] = tmp;
39+
return (found);
40+
}
41+
};

0 commit comments

Comments
ย (0)