< BFS >
#include <iostream>
#include <queue>
// x가 행, y가 열
#define X first
#define Y second
int board[502][502] =
{ {1,1,1,0,1,0,0,0,0,0},
{1,0,0,0,1,0,0,0,0,0},
{1,1,1,0,1,0,0,0,0,0},
{1,1,0,0,1,0,0,0,0,0},
{0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0} };
bool visited[502][502];
int n = 7, m = 10;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
int main()
{
//std::ios::sync_with_stdio(0);
//std::cin.tie(0);
std::queue<std::pair<int, int>> queue;
visited[0][0] = 1;
queue.push({ 0,0 });
while (!queue.empty()) {
std::pair<int, int> cur = queue.front();
queue.pop();
std::cout << '(' << cur.X << ", " << cur.Y << ") -> ";
for (int dir = 0; dir < 4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx < 0 || nx >= n || ny < 0 || ny >= m)
continue;
if (visited[nx][ny] || board[nx][ny] != 1)
continue;
visited[nx][ny] = 1;
queue.push({ nx, ny });
}
}
}
< DFS >
#include <iostream>
#include <stack>
// x가 행, y가 열
#define X first
#define Y second
int board[502][502] =
{ {1,1,1,0,1,0,0,0,0,0},
{1,0,0,0,1,0,0,0,0,0},
{1,1,1,0,1,0,0,0,0,0},
{1,1,0,0,1,0,0,0,0,0},
{0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0} };
bool visited[502][502];
int n = 7, m = 10;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
int main()
{
//std::ios::sync_with_stdio(0);
//std::cin.tie(0);
std::stack<std::pair<int, int>> stack;
visited[0][0] = 1;
stack.push({ 0,0 });
while (!stack.empty()) {
std::pair<int, int> cur = stack.top();
stack.pop();
std::cout << '(' << cur.X << ", " << cur.Y << ") -> ";
for (int dir = 0; dir < 4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx < 0 || nx >= n || ny < 0 || ny >= m)
continue;
if (visited[nx][ny] || board[nx][ny] != 1)
continue;
visited[nx][ny] = 1;
stack.push({ nx, ny });
}
}
}
< 참고자료 >
[실전 알고리즘] 0x09강 - BFS
안녕하세요 여러분, 드디어 올 것이 왔습니다. 마음의 준비를 단단히 하셔야 합니다.. 드디어 실전 알고리즘 강의에서 첫 번째 고비에 도달했는데 이 강의와 함께 이번 고비를 잘 헤쳐나가면 좋
blog.encrypted.gg
[실전 알고리즘] 0x0A강 - DFS
드디어 01 02 03 이렇게 숫자를 넘어서 0A강에 도달했습니다. 아직 완결까지는 한참 남았지만 아무튼 힘을 내서 계속 잘 해봅시다. 아, 참고로 저번 단원보다는 내용이 많지 않아서 편한 마음으로
blog.encrypted.gg
'CS > C++' 카테고리의 다른 글
| C++로 이진탐색(BinarySearch) (0) | 2023.08.22 |
|---|---|
| C++ 정수, 실수 자료형 범위와 주의할 점 (0) | 2023.07.21 |
| [C++] Vector VS List (0) | 2023.07.20 |
| C++ Deque VS Vector (0) | 2023.07.12 |
| C++로 덱 구현 (0) | 2023.07.11 |