BOJ::1260 DFS와 BFS
https://www.acmicpc.net/problem/1260
DFS, BFS의 완전완전완전완전 기본 문제이다.
JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; class Main{ static int n,m,v; static int map[][]; static boolean check[]; public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n=Integer.parseInt(st.nextToken()); m=Integer.parseInt(st.nextToken()); v=Integer.parseInt(st.nextToken()); map=new int[n+1][n+1]; for(int i = 0 ; i < m ; i++){ st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); map[x][y]=1; map[y][x]=1; } check = new boolean[n+1]; dfs(v); System.out.println(); check = new boolean[n+1]; bfs(v); } public static void dfs(int v){ System.out.print(v +" "); check[v]=true; for(int i = 1 ; i <= n ; i++){ if(map[v][i]==1 && !check[i]){ dfs(i); } } } public static void bfs(int v){ Queue<Integer> q = new LinkedList(); q.add(v); check[v]=true; while(!q.isEmpty()){ int next = q.poll(); System.out.print(next +" "); for(int i = 1 ; i <= n ; i++){ if(map[next][i] ==1 && !check[i]){ q.add(i); check[i]=true; } } } } } | cs |
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <iostream> #include <queue> using namespace std; int n, m, v; int map[1001][1001]; bool check[10001]; void bfs(int v) { queue<int> q; q.push(v); check[v] = true; while (!q.empty()) { int next = q.front(); q.pop(); cout << next << " "; for (int i = 1; i <= n; i++) { if (map[next][i] == 1 && !check[i]) { q.push(i); check[i] = true; } } } } void dfs(int v) { cout << v << " "; check[v] = true; for (int i = 1; i <= n; i++) { if (map[v][i] == 1 && !check[i]) { dfs(i); } } } int main() { cin >> n >> m >> v; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; map[x][y] = 1; map[y][x] = 1; } dfs(v); cout << endl; for (int i = 1; i <= n; i++) { check[i] = false; } bfs(v); } | cs |
'BOJ::문제풀이' 카테고리의 다른 글
1309 동물원 (0) | 2017.12.31 |
---|---|
1302 베스트 셀러 (0) | 2017.12.31 |
1157 이상한 곱셈 (0) | 2017.12.30 |
1157 단어 공부 (0) | 2017.12.30 |
1152 단어의 개수 (0) | 2017.12.30 |