"BOJ 2606 바이러스"의 두 판 사이의 차이

(새 문서: ==개요== 분류: 너비 우선 탐색 {{BOJ|단계=31}} ==C++== <syntaxhighlight lang='cpp'> #include <bits/stdc++.h> using namespace std; int N, M; vector<int> G[101]; bool v...)
 
 
(같은 사용자의 중간 판 5개는 보이지 않습니다)
1번째 줄: 1번째 줄:
==개요==
==개요==
[[분류: 너비 우선 탐색]]
{{BOJ|단계=31
{{BOJ|단계=31}}
|분류1=너비 우선 탐색
|분류2=깊이 우선 탐색
}}


==C++==
==C++==
{{소스헤더|BFS}}
<syntaxhighlight lang='cpp'>
<syntaxhighlight lang='cpp'>
#include <bits/stdc++.h>
#include <bits/stdc++.h>
12번째 줄: 15번째 줄:
bool visited[101];
bool visited[101];
int cnt = 0;
int cnt = 0;
int u, v;


void bfs() {
void bfs() {
     queue<int> q;
     queue<int> q;
visited[1] = true;
     q.push(1);
     q.push(1);
cnt++;
visited[1] = true;
int u, v;
while(!q.empty()) {
while(!q.empty()) {
    u = q.front();
    u = q.front();
36번째 줄: 38번째 줄:
scanf("%d", &N);
scanf("%d", &N);
scanf("%d", &M);
scanf("%d", &M);
int a, b;
for(int i=0; i<M; i++) {
for(int i=1; i<=M; i++) {
scanf("%d %d", &u, &v);
scanf("%d %d", &a, &b);
G[u].push_back(v);
G[a].push_back(b);
G[v].push_back(u);
G[b].push_back(a);
}
}
bfs();
bfs();
printf("%d", cnt-1);
printf("%d", cnt);
}
</syntaxhighlight>
 
{{소스헤더|DFS}}
<syntaxhighlight lang='cpp'>
#include <bits/stdc++.h>
using namespace std;
 
int N, M;
vector<int> G[101];
bool visited[101];
int cnt = -1;
int u, v;
 
void dfs(int x) {
if (visited[x]) {
return;
}
visited[x] = true;
cnt++;
for (int i=0; i<G[x].size(); i++) {
dfs(G[x][i]);
}
}
 
int main() {
scanf("%d", &N);
scanf("%d", &M);
for(int i=0; i<M; i++) {
scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1);
printf("%d", cnt);
}
}
</syntaxhighlight>
</syntaxhighlight>

2023년 12월 23일 (토) 20:30 기준 최신판

1 개요[ | ]

BOJ 2606 바이러스

2 C++[ | ]

BFS
#include <bits/stdc++.h>
using namespace std;

int N, M;
vector<int> G[101];
bool visited[101];
int cnt = 0;
int u, v;

void bfs() {
    queue<int> q;
	visited[1] = true;
    q.push(1);
	while(!q.empty()) {
	    u = q.front();
	    q.pop();
	    for(int i=0; i<G[u].size(); i++) {
	        v = G[u][i];
	        if(!visited[v]) {
	            cnt++;
	            visited[v] = true;
	            q.push(v);
	        }
	    }
	}
}

int main() {
	scanf("%d", &N);
	scanf("%d", &M);
	for(int i=0; i<M; i++) {
		scanf("%d %d", &u, &v);
		G[u].push_back(v);
		G[v].push_back(u);
	}
	bfs();
	printf("%d", cnt);
}
DFS
#include <bits/stdc++.h>
using namespace std;

int N, M;
vector<int> G[101];
bool visited[101];
int cnt = -1;
int u, v;

void dfs(int x) {
	if (visited[x]) {
		return;
	}
	visited[x] = true;
	cnt++;
	for (int i=0; i<G[x].size(); i++) {
		dfs(G[x][i]); 
	}
}

int main() {
	scanf("%d", &N);
	scanf("%d", &M);
	for(int i=0; i<M; i++) {
		scanf("%d %d", &u, &v);
		G[u].push_back(v);
		G[v].push_back(u);
	}
	dfs(1);
	printf("%d", cnt);
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}