๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โœจ Algorithm/๐Ÿ•‍๐Ÿฆบ ๋ฐ”ํ‚น๋… ๊ฐœ๋…

[0x0A] DFS

by nitronium102 2023. 6. 26.

DFS depth first search

๋‹ค์ฐจ์› ๋ฐฐ์—ด์—์„œ ๊ฐ ์นธ์„ ๋ฐฉ๋ฌธํ•  ๋•Œ ๊นŠ์ด๋ฅผ ์šฐ์„ ์œผ๋กœ ๋ฐฉ๋ฌธํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

์˜ˆ์‹œ

๋ชจ๋“  ์นธ์ด ์Šคํƒ์— 1๋ฒˆ์”ฉ ๋“ค์–ด๊ฐ€๋ฏ€๋กœ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ์นธ์ด N๊ฐœ์ผ ๋•Œ O(N)

  1. ์‹œ์ž‘ํ•˜๋Š” ์นธ์„ ์Šคํƒ์— ๋„ฃ๊ณ  ๋ฐฉ๋ฌธํ•˜๋Š” ํ‘œ์‹œ๋ฅผ ๋‚จ๊น€
  2. ์Šคํƒ์—์„œ ์›์†Œ๋ฅผ ๊บผ๋‚ด์„œ ๊ทธ ์นธ๊ณผ ์ƒํ•˜์ขŒ์šฐ๋กœ ์ธ์ ‘ํ•œ ์นธ์— ๋Œ€ํ•ด (3)์„ ์ง„ํ–‰
  3. ํ•ด๋‹น ์นธ์„ ์ด์ „์— ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด ์•„๋ฌด ๊ฒƒ๋„ ํ•˜์ง€ ์•Š๊ณ , ์ฒ˜์Œ์œผ๋กœ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋Š” ํ‘œ์‹œ๋ฅผ ๋‚จ๊ธฐ๊ณ  ํ•ด๋‹น ์นธ์„ ์Šคํƒ์— ์‚ฝ์ž…
  4. ์Šคํƒ์ด ๋นŒ ๋•Œ๊นŒ์ง€ (2)๋ฅผ ๋ฐ˜๋ณต
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second // pair์—์„œ first, second๋ฅผ ์ค„์—ฌ์„œ ์“ฐ๊ธฐ ์œ„ํ•ด์„œ ์‚ฌ์šฉ
int board[502][502] = { ... }; // 1์ด ํŒŒ๋ž€ ์นธ, 0์ด ๋นจ๊ฐ„ ์นธ์— ๋Œ€์‘
bool vis[502][502]; // ํ•ด๋‹น ์นธ์„ ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ์ €์žฅ
int n = 7, m = 10; // n = ํ–‰์˜ ์ˆ˜, m = ์—ด์˜ ์ˆ˜
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1}; // ์ƒํ•˜์ขŒ์šฐ ๋„ค ๋ฐฉํ–ฅ์„ ์˜๋ฏธ

int main(void){
  ios::sync_with_stdio(0);
  cin.tie(0);

  stack<pair<int,int> > S;

  vis[0][0] = 1; // (0, 0)์„ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๊ณ  ๋ช…์‹œ
  S.push({0,0}); // ์Šคํƒ์— ์‹œ์ž‘์ ์ธ (0, 0)์„ ์‚ฝ์ž….

  while(!S.empty()){
    pair<int,int> cur = S.top(); S.pop();
    cout << '(' << cur.X << ", " << cur.Y << ") -> ";

    for(int dir = 0; dir < 4; dir++){ // ์ƒํ•˜์ขŒ์šฐ ์นธ์„ ์‚ดํŽด๋ณผ ๊ฒƒ์ด๋‹ค.
      int nx = cur.X + dx[dir];
      int ny = cur.Y + dy[dir]; // nx, ny์— dir์—์„œ ์ •ํ•œ ๋ฐฉํ–ฅ์˜ ์ธ์ ‘ํ•œ ์นธ์˜ ์ขŒํ‘œ๊ฐ€ ๋“ค์–ด๊ฐ
      if(nx < 0 || nx >= n || ny < 0 || ny >= m) continue; // ๋ฒ”์œ„ ๋ฐ–์ผ ๊ฒฝ์šฐ ๋„˜์–ด๊ฐ
      if(vis[nx][ny] || board[nx][ny] != 1) continue; // ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ์นธ์ด๊ฑฐ๋‚˜ ํŒŒ๋ž€ ์นธ์ด ์•„๋‹ ๊ฒฝ์šฐ
      vis[nx][ny] = 1; // (nx, ny)๋ฅผ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๊ณ  ๋ช…์‹œ
      S.push({nx,ny});
    }
  }
}

BFS vs DFS

  • bfs : ํ˜„์žฌ ์นธ์—์„œ ์ธ์ ‘ํ•œ ์นธ์€ ํ˜„์žฌ ์นธ์—์„œ ๊ฑฐ๋ฆฌ๊ฐ€ 1๋งŒํผ ๋–จ์–ด์ ธ ์žˆ๋‹ค

'โœจ Algorithm > ๐Ÿ•โ€๐Ÿฆบ ๋ฐ”ํ‚น๋… ๊ฐœ๋…' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[0x09] BFS  (0) 2023.06.26
[0x08] ์Šคํƒ์˜ ํ™œ์šฉ(์ˆ˜์‹์˜ ๊ด„ํ˜ธ ์Œ)  (0) 2023.06.26
[0x07] ๋ฑ  (0) 2023.06.26
[0x06] ํ  (0) 2023.06.20
[0x05] ์Šคํƒ  (0) 2023.06.20

๋Œ“๊ธ€