Baekjoon

[백준/BOJ]1260번 DFS와 BFS

developerwkddbs 2024. 11. 6. 14:01
#include <stdio.h>
#include <stdlib.h>
#define MAX 1001 //1<=N<=1000
int DFS_V[MAX]={0}; //dfs 실행 지난 정점 개수
int BFS_V[MAX]={0}; //bfs 실행 지난 정점 개수
int graph[MAX][MAX]={0}; //graph 초기화
int queue[MAX];

//bfs 구동을 위한 function
void bfs(int v, int vertise)
{
    int w;
    int front, rear, pop;
    front=rear=0; //stack의 front와 rear을 초기화
    printf("%d ",v);
    BFS_V[v]=1;
    queue[0]=v; rear++;
    while(front<rear) //front==rear일 때, 반복을 종료한다.
    {
        pop=queue[front]; front++; //front의 정보를 빼고 n+1번째 배열을 front로 지정
        for(w=1; w<=vertise; w++)
        {
            if(graph[pop][w]==1 && BFS_V[w]==0)
            {
                printf("%d ",w);
                queue[rear]=w; rear++;
                BFS_V[w]=1;
            }
        }
    }
}

//dfs구동을 위한 function
void dfs(int v, int vertise)
{
    int w;
    DFS_V[v]=1;
    printf("%d ",v);
    for(w=1; w<=vertise; w++)
    {
        if(graph[v][w]==1&&DFS_V[w]==0)
        {
            dfs(w,vertise);
        }
    }
}

int main()
{
    int vertices, edges, vertex, i, j;
    scanf("%d %d %d",&vertices,&edges,&vertex);
    if(vertices<1||vertices>1000||edges<1||edges>10000)
        exit(0);
    while(edges--)
    {
        scanf("%d %d",&i,&j);
        graph[i][j]=1;
        graph[j][i]=1;
    }

    dfs(vertex,vertices);
    printf("\n");
    bfs(vertex,vertices);
    printf("\n");

    return 0;
}

질문 및 수정사항은 <비밀댓글> 써주세요.