BOJ 1987. μνλ²³
πββοΈ[Gold IV] μνλ²³ - 1987
μ±λ₯ μμ½
λ©λͺ¨λ¦¬: 2028 KB, μκ°: 1624 ms
λΆλ₯
λ°±νΈλνΉ, κΉμ΄ μ°μ νμ, κ·Έλν μ΄λ‘ , κ·Έλν νμ
μ μΆ μΌμ
2024λ 1μ 17μΌ 10:31:40
λ¬Έμ μ€λͺ
μΈλ‘
λ§μ μνμ’μ°λ‘ μΈμ ν λ€ μΉΈ μ€μ ν μΉΈμΌλ‘ μ΄λν μ μλλ°, μλ‘ μ΄λν μΉΈμ μ ν μλ μνλ²³μ μ§κΈκΉμ§ μ§λμ¨ λͺ¨λ μΉΈμ μ ν μλ μνλ²³κ³Όλ λ¬λΌμΌ νλ€. μ¦, κ°μ μνλ²³μ΄ μ ν μΉΈμ λ λ² μ§λ μ μλ€.
μ’μΈ‘ μλ¨μμ μμν΄μ, λ§μ΄ μ΅λν λͺ μΉΈμ μ§λ μ μλμ§λ₯Ό ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€. λ§μ΄ μ§λλ μΉΈμ μ’μΈ‘ μλ¨μ μΉΈλ ν¬ν¨λλ€.
μ λ ₯
첫째 μ€μ
μΆλ ₯
첫째 μ€μ λ§μ΄ μ§λ μ μλ μ΅λμ μΉΈ μλ₯Ό μΆλ ₯νλ€.
πνμ΄
DFSλ¬Έμ λ‘ λ°±νΈλνΉμ ν΄μΌνλ€.
μ²μμ BFSλ‘ μ κ·Όνλ€κ° μνλ €μ λ€μ νλ€.
charλ₯Ό κΈ°λ‘νλ λ°°μ΄μ λ§λ€μ΄μ μλ‘ μΆκ°ν μνλ²³μ΄ κΈ°μ‘΄μ λ±λ‘λμ΄ μλμ§ νμΈνλ©΄μ DFSλ₯Ό λλ €μΌνλ€.
int dy[] = { -1, 0, 1, 0 };
int dx[] = { 0, 1, 0, -1 };
int seqSize = 1;
void DFS(pair<int, int> here)
{
ch[seqSize++] = board[here.first][here.second];
res = max(res, seqSize);
// κΈ°λ‘λ ch νμΈμ©
//cout << endl;
//cout << "νμ¬ ch μν " << endl;
//for (int i = 1; i <= seqSize; ++i)
//{
// cout << ch[i] << " ";
//}
//cout << endl;
for (int i = 0; i < 4; ++i)
{
int ny = here.first + dy[i];
int nx = here.second + dx[i];
if (ny < 1 || nx < 1 || ny > r || nx > c)
continue;
if (visited[ny][nx] == 1)
continue;
bool flag = false;
for (int j = 1; j <= seqSize; ++j)
{
if (ch[j] == board[ny][nx])
{
flag = true;
break;
}
}
if (flag == true)
continue;
visited[ny][nx] = 1;
DFS({ ny, nx });
visited[ny][nx] = 0;
ch[--seqSize] = ' ';
}
}
μλ₯Ό λ€μ΄ μλμ κ°μ μ λ ₯μ΄ λ€μ΄μ€λ©΄
2 4
CAAB
ADCB
μλμ κ°μ κ²°κ³Όλ₯Ό 보μΈλ€.
πμ 체 μ½λ
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int r, c, res = 0;
char ch[500];
vector<vector<char>> board;
vector<vector<int>> visited;
void setting()
{
cin >> r >> c;
board = vector<vector<char>>(r + 1, vector<char>(c + 1));
visited = vector<vector<int>>(r + 1, vector<int>(c + 1));
string str;
for (int i = 1; i <= r; ++i)
{
cin >> str;
for (int j = 0; j < str.size(); ++j)
{
board[i][j + 1] = str[j];
}
}
}
int dy[] = { -1, 0, 1, 0 };
int dx[] = { 0, 1, 0, -1 };
int seqSize = 1;
void DFS(pair<int, int> here)
{
ch[seqSize++] = board[here.first][here.second];
res = max(res, seqSize);
//cout << endl;
//cout << "νμ¬ ch μν " << endl;
//for (int i = 1; i <= seqSize; ++i)
//{
// cout << ch[i] << " ";
//}
//cout << endl;
for (int i = 0; i < 4; ++i)
{
int ny = here.first + dy[i];
int nx = here.second + dx[i];
if (ny < 1 || nx < 1 || ny > r || nx > c)
continue;
if (visited[ny][nx] == 1)
continue;
bool flag = false;
for (int j = 1; j <= seqSize; ++j)
{
if (ch[j] == board[ny][nx])
{
flag = true;
break;
}
}
if (flag == true)
continue;
visited[ny][nx] = 1;
DFS({ ny, nx });
visited[ny][nx] = 0;
ch[--seqSize] = ' ';
}
}
void solve()
{
DFS({ 1, 1 });
cout << res - 1;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
//freopen("input.txt", "rt", stdin);
setting();
solve();
return 0;
}