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β€Ž

Lines changed: 41 additions & 0 deletions
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)