Notice
Recent Posts
Recent Comments
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
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
Tags more
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐ŸŒฒ์ž๋ผ๋‚˜๋Š”์ฒญ๋…„

array list์™€ Dfs, bfs(java) ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด

array list์™€ Dfs, bfs(java)

JihyunLee 2019. 4. 2. 10:17
๋ฐ˜์‘ํ˜•
package ch6;
//array ๋กœ graph ๊ตฌํ˜„ 
/*
 * ์˜ˆ์ œ์ž…๋ ฅ 
 * 4 5 1	์ •์ ์˜์ˆ˜, ๊ฐ„์„ ์˜์ˆ˜, ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ๋ฒˆ
	1 2
	1 3
	1 4
	2 4
	3 4
 */

import java.util.*;
public class graph_array {
	static int[] check;
	static int[][] a;
	static int n=0;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		n = scan.nextInt();// node์˜ ์ˆ˜ 
		check = new int[n+1];
		
		a = new int[n+1][n+1];
		int num = scan.nextInt();//๊ฐ„์„ ์˜ ์ˆ˜  
		int start = scan.nextInt();//ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ๋ฒˆํ˜ธ 
		
		for(int i=0; i<num; i++) {
			int v = scan.nextInt();
			int w = scan.nextInt();
			a[v][w] = a[w][v] = 1;
		}
		//์ธ์ ‘์–ด๋ ˆ์ด  ํ™•์ธ  
//		for(int i=1; i<n+1; i++) {
//			for(int j=1; j<n+1; j++) {
//				System.out.print(a[i][j] + " ");
//			}
//			System.out.println("");
//		}
		
		//dfs_r(start);
		dfs_s(start);
		for(int i=0; i<n+1;i++) {
			check[i]=0;
		}
		System.out.println("");
		bfs(start);
		
		
 		

	}
	//recurrsive๋กœ ๊ตฌํ˜„ํ•œ dfs
	public static void dfs_r(int node) {
		if(check[node]==0) {
			System.out.print(node + " ");
			check[node]=1;
		}
		for(int i=1;i<n+1;i++) {
			if(check[i]==0&&a[node][i]==1)	dfs_r(i);
		}
		return;
	}
	
	//stack์œผ๋กœ ๊ตฌํ˜„ํ•œ dfs
	public static void dfs_s(int v) {
		Stack<Integer> stack = new Stack<>();
		System.out.print(v+" ");
		check[v]=1;
		stack.add(v);
		
		while (!stack.isEmpty()) {
			boolean flag = false;
			int vv = stack.peek();
			for(int i=1;i<n+1;i++) {
				if(a[vv][i]==1&&check[i]==0) {
					flag = true;
					System.out.print(i+" ");
					stack.add(i);
					check[i]=1;
					break;
				}
			}
			if(flag==false)
				stack.pop();
		}
	}
	
	//bfs
	public static void bfs(int v) {
		Queue<Integer> q = new LinkedList<>();
		q.add(v);
		System.out.print(v+" ");
		check[v]=1;
		while(!q.isEmpty()) {
			v=q.poll();
			for(int i=1;i<n+1;i++) {
				if(a[v][i]==1&&check[i]==0) {
					q.add(i);
					check[i]=1;
					System.out.print(i+" ");
				}
			}
		}
		
		return;
	}
	

}
๋ฐ˜์‘ํ˜•