Skip to content

Commit bf2a30b

Browse files
committed
4주차 문제 풀이 1개 추가
- Word Search
1 parent 05c5770 commit bf2a30b

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

word-search/hwi-middle.cpp

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Solution {
2+
private:
3+
int row;
4+
int col;
5+
6+
public:
7+
bool exist(vector<vector<char>>& board, string word) {
8+
row = board.size();
9+
col = board[0].size();
10+
for (int r = 0; r < row; ++r)
11+
{
12+
for (int c = 0; c < col; ++c)
13+
{
14+
if (solve(board, word, r, c, 0))
15+
{
16+
return true;
17+
}
18+
}
19+
}
20+
21+
return false;
22+
}
23+
24+
// dfs 함수
25+
bool solve(vector<vector<char>>& board, string& word, int r, int c, int idx)
26+
{
27+
// 범위를 벗어난 경우
28+
if (r < 0 || r >= row || c < 0 || c >= col)
29+
{
30+
return false;
31+
}
32+
33+
// 글자가 맞지 않는 경우
34+
if (board[r][c] != word[idx])
35+
{
36+
return false;
37+
}
38+
39+
// 단어를 찾은 경우
40+
if (idx == word.size() - 1)
41+
{
42+
return true;
43+
}
44+
45+
char ch = board[r][c];
46+
board[r][c] = '?'; // 이미 방문한 곳으로 돌아오지 않도록 입력으로 들어오지 않는 문자로 치환
47+
48+
// 상하좌우 탐색
49+
int dr[4] = { 1, 0, -1, 0 };
50+
int dc[4] = { 0, 1, 0, -1 };
51+
52+
for (int dir = 0; dir < 4; ++dir)
53+
{
54+
int nr = r + dr[dir];
55+
int nc = c + dc[dir];
56+
if (solve(board, word, nr, nc, idx + 1))
57+
{
58+
return true;
59+
}
60+
}
61+
62+
board[r][c] = ch; // 원래 문자로 되돌리기
63+
return false;
64+
}
65+
};

0 commit comments

Comments
 (0)