반응형
https://www.acmicpc.net/problem/1987
1987번: 알파벳
세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으
www.acmicpc.net
와이 시간초과??
#include <iostream> // 시간초과
#include <string>
#include <vector>
#include <algorithm>
#include <deque>
#include <unordered_set>
using namespace std;
int col, row, res = -1;
vector<string> board;
unordered_set<char> s;
int dx[4] = {1, 0,-1 ,0};
int dy[4] = {0, -1, 0 ,1};
void dfs(int depth, int x, int y) {
if (s.find(board[x][y]) != s.end()) {
res = max(depth, res);
return ;
}
s.insert(board[x][y]);
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
if (newX < 0 || newY < 0 || newX >= col || newY >= row)
continue;
dfs(depth + 1, newX, newY);
}
s.erase(board[x][y]);
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0);
cin >> col >> row;
for (int i = 0; i < col; i++) {
string input;
cin >> input;
board.push_back(input);
}
dfs(0, 0, 0);
cout << res;
}
unordered_set으로 O(1)에 가깝게 탐색해도 시간초과로 터진다. bool visit배열을 만들어서 해결했다.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <deque>
#include <unordered_set>
#include <cstring>
using namespace std;
int col, row, res = -1;
vector<string> board;
bool visit[27];
int dx[4] = {1, 0,-1 ,0};
int dy[4] = {0, -1, 0 ,1};
void dfs(int depth, int x, int y) {
if (visit[board[x][y] - 'A'] == true) {
res = max(depth, res);
return ;
}
visit[board[x][y] - 'A'] = true;
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
if (newX < 0 || newY < 0 || newX >= col || newY >= row)
continue;
dfs(depth + 1, newX, newY);
}
visit[board[x][y] - 'A'] = false;
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0);
cin >> col >> row;
memset(visit, 0, sizeof(visit));
for (int i = 0; i < col; i++) {
string input;
cin >> input;
board.push_back(input);
}
if (col == 1 && row == 1) { ////////////// 재채점 아놔
cout << 1;
return 0;
}
dfs(0, 0, 0);
cout << res;
}
갑자기 재채점 됐대서 들어가 보니까 98프로에서 터지더라.
딱 봐도
1 1
A
이거같아서 예외케이스 처리 해 줬다.
어이업성
반응형
'<algorithm> > 백준' 카테고리의 다른 글
백준 18111 마인크래프트 c++ (0) | 2023.09.17 |
---|---|
백준 18110 solved.ac c++ (0) | 2023.09.17 |
백준 1931 회의실 배정 c++ (0) | 2023.09.15 |
백준 9935 문자열 폭발 c++ (0) | 2023.09.12 |
백준 11866 요세푸스 문제 0 c++ (0) | 2023.09.11 |