" (๋ฐฑ์ค/c++) 1987 - ์ํ๋ฒณ/ DFS, ๋ฐฑํธ๋ํน"
https://www.acmicpc.net/problem/1987
๐ solved.ac ๋์ด๋: ๊ณจ๋4
BFS๋ก ํ์๋ค๊ฐ ~ DFS์ Set์ ํจ๊ปํด์ ํ์๋ค๊ฐ ์๊ฐ์ด๊ณผ๋ก ๋งํ์ Set์ ์์ ๊ณ ๋ฌธ์ ๋ฅผ ํ์๋ค..
๐ธ BFS๋ก ํ์์ ๋ ๋์๋ ์ด์
- BFS๋ ๋์ด ์ฐ์ ์ผ๋ก ๋นจ๊ฐ์์ผ๋ก ์ฒดํฌํ ๋ถ๋ถ์ด ์ด์ ํ๋์ Que์ [F]๊ฐ ๋ด๊ฒจ ํ๋์[E] ์ฃผ๋ณ ๋
ธ๋์[H] [F]์ ๋ด์ผ๋ ค ํ ๋ [F]๊ฐ ๋น ์ง๊ฒ ๋๋ค.
๐ธ DFS + Set ํ์ด
Set์ผ๋ก findํด์ ์ง๋๊ฐ ๊ฒฝ๋ก์ ํ์ฌ ์ํ๋ฒณ์ด ํฌํจ๋์๋์ง ํ์ธํ๋ ค๊ณ ํ๋ค.
- Set์ find ์๊ฐ๋ณต์ก๋๋ O(logN)
- ๋ฐฐ์ด์ ๋ฐ๋ก ์ ๊ทผ ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ O(1)
set<char> alphabets;
alphabets.find(Arr[next_x][next_y]) == alphabets.end()
๐ธ ํ์ธํ ๋ถ๋ถ
์์ํ๋ ๊ตฌ๊ฐ์์ alphabet ์ ๋ณด์ ๋ฐฉ๋ฌธ ์ ๋ณด๋ฅผ ๋ชจ๋ false์ด์ผ์ค๋ค. ์ฒซ ์์ ๋ถ๋ถ์ ์ (1, 0), (0, 1) ๋ง pCount์๋ค์ด์ค๊ฒ ๋ ๊ฑฐ๋ค.
์ ์ฝ๋๋ฅผ ๋ณด๋ฉด for (int i = 0; i < 4; ++i) ๋ฅผ ๋น ์ ธ๋๊ฐ๋ฉด ํ์ฌ ๋ฐฉ๋ฌธ์ false ์์ผ์ค๋น
์ต์ข ์ฝ๋
#include<iostream>
#include<queue>
#include<memory.h>
using namespace std;
int dx[4] = { -1, 1, 0 , 0 };
int dy[4] = { 0, 0, 1, -1 };
char Arr[21][21];
bool visited[21][21] = { false, };
queue<pair<int, int>> que;
bool alphabets[26] = {false, };
int R, C;
int Results = 0;
int AlphabetToNum(char pChr)
{
return pChr - 'A';
}
void DFS(int x, int y, int pCount)
{
alphabets[AlphabetToNum(Arr[x][y])] = true;
for (int i = 0; i < 4; ++i)
{
int next_x = dx[i] + x;
int next_y = dy[i] + y;
if (pCount == 0)
{
memset(alphabets, false, sizeof(alphabets));
alphabets[AlphabetToNum(Arr[x][y])] = true;
memset(visited, false, sizeof(visited));
visited[x][y] = true;
}
if (alphabets[AlphabetToNum(Arr[next_x][next_y])] == false
&& next_x >= 0 && next_x < R && next_y >= 0 && next_y < C
&& visited[next_x][next_y] == false)
{
visited[next_x][next_y] = true;
DFS(next_x, next_y, pCount + 1);
}
if (Results < pCount)
{
Results = pCount;
}
}
visited[x][y] = false;
alphabets[AlphabetToNum(Arr[x][y])] = false;
}
int main(void)
{
cin >> R >> C;
for (int i = 0; i < R; ++i)
{
for (int j = 0; j < C; ++j)
{
char chr;
cin >> chr;
Arr[i][j] = chr;
}
}
DFS(0, 0, 0);
cout << Results + 1;
return 0;
}
'๐ coding test > โฝ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
(๋ฐฑ์ค/c++) 1238 - ํํฐ / ์ต๋จ๊ฒฝ๋ก๊ทธ๋ํ, ํ๋ก์ด๋ ์์ฌ (0) | 2024.08.22 |
---|---|
(๋ฐฑ์ค/c++) 10026 - ์ ๋ก์์ฝ / BFS, ๊ทธ๋ํ (0) | 2024.08.20 |
(๋ฐฑ์ค/c++) 11403 - ๊ฒฝ๋ก์ฐพ๊ธฐ / BFS, ๊ทธ๋ํ (0) | 2024.08.16 |
(๋ฐฑ์ค/c++) 11724 - ์ฐ๊ฒฐ ์์์ ๊ฐ์ / BFS, ๊ทธ๋ํ (0) | 2024.08.16 |
(๋ฐฑ์ค/c++) 14940 - ์ฌ์ด ์ต๋จ ๊ฑฐ๋ฆฌ / DFS, ๊ทธ๋ํ (0) | 2024.08.16 |
์ ํ๋ ๊ฒ ๋ณด๋ค ๋ซ๊ฒ ์ง
ํฌ์คํ ์ด ์ข์๋ค๋ฉด "์ข์์โค๏ธ" ๋๋ "๊ตฌ๋ ๐๐ป" ํด์ฃผ์ธ์!