문제 링크입니다: www.acmicpc.net/problem/1952
1952번: 달팽이2
M줄 N칸으로 되어 있는 표 위에, 달팽이 모양으로 선을 그리려고 한다. 위의 그림은 M=5, N=3의 예이다. 이제 표의 왼쪽 위 칸(ㅇ)에서 시작하여, 오른쪽으로 선을 그려 나간다. 표의 바깥 또는 이미
www.acmicpc.net
분명 수학적으로 풀 수 있을 것 같지만 전 BFS 방식으로 풀었습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <queue> | |
using namespace std; | |
const int MAX = 100; | |
const int MAX_DIR = 4; | |
typedef struct | |
{ | |
int y, x; | |
}Coord; | |
typedef struct | |
{ | |
int y, x; | |
}Dir; | |
Dir moveDir[MAX_DIR] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
int M, N; | |
cin >> M >> N; | |
bool visited[MAX][MAX] = { false, }; | |
visited[0][0] = true; | |
int result = 0; | |
int dir = 0; | |
queue<Coord> q; | |
q.push({ 0, 0 }); | |
while (!q.empty()) | |
{ | |
Coord cur = q.front(); | |
int y = cur.y; | |
int x = cur.x; | |
q.pop(); | |
for (int i = 0; i < 2; i++) | |
{ | |
dir = (dir + i) % MAX_DIR; | |
int nextY = y + moveDir[dir].y; | |
int nextX = x + moveDir[dir].x; | |
if (nextY < 0 || nextY >= M || nextX < 0 || nextX >= N) | |
{ | |
continue; | |
} | |
if (visited[nextY][nextX]) | |
{ | |
continue; | |
} | |
// 꺾었다는 뜻 | |
if (i == 1) | |
{ | |
result++; | |
} | |
visited[nextY][nextX] = true; | |
q.push({ nextY, nextX }); | |
break; | |
} | |
} | |
cout << result << "\n"; | |
return 0; | |
} |


개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 1975번 Number Game (0) | 2021.04.09 |
---|---|
백준 21300번 Bottle Return (2) | 2021.04.08 |
백준 1942번 디지털시계 (2) | 2021.04.06 |
백준 1864번 문어 숫자 (0) | 2021.04.06 |
백준 1837번 암호제작 (0) | 2021.04.04 |