Mini

백준 1260 //dfs-bfs하는법 , 연결정보준경우 본문

Algorithm/boj

백준 1260 //dfs-bfs하는법 , 연결정보준경우

Mini_96 2023. 5. 1. 15:55

1260번: DFS와 BFS (acmicpc.net)

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

* bfs 하는법

1.q메이커

2.push

3.while(size)

4.연결됨 & 미방문 -> push, 방문처리

#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int n, m,v,t1,t2,  a[1004][1004], visited[1004];
int dx[] = {0,1,-1,0};
int dy[] = {1,0,0,-1};
vector<int> ret;

void dfs(int here)
{
    visited[here] = 1;
    cout << here << " ";

    for (int there = 0; there < 1004; ++there)
    {
        if (a[here][there] == 1 && visited[there] == 0)
            dfs(there);
    }
    return;

}

void bfs(int start)
{
    queue<int> q;
    q.push(start);
    //visit[start] = 1;
    //cout << start << " ";
    int here;

    while (q.size())
    {
        here = q.front(); q.pop();
        visited[here] = 1;
        cout << here << " ";
        for (int there = 0; there < 1004; ++there)
        {
            if (a[here][there] == 1 && visited[there] == 0)
            {
                q.push(there);
                visited[there] = 1;
            }
        }
    }
}

int main() {
    ios_base::sync_with_stdio(0); cin.tie(NULL);
    cin >> n>>m>>v;
    
    for (int i = 0; i < m; ++i)
    {
        cin >> t1 >> t2;
        a[t1][t2] = 1;
        a[t2][t1] = 1;
    }

    dfs(v);
    for (int i = 0; i < 1004; ++i) visited[i] = 0;
    cout << "\n";
    bfs(v);

    return 0;
}