반응형
public class Q_1260 {
	
	static boolean[] dfsCheck;
	static boolean[] bfsCheck;
	static int[][] map;
	
	static void bfs(int start) {
		Queue<Integer> q = new LinkedList<>();
		
		q.offer(start);
		bfsCheck[start] = true;
		
		while(!q.isEmpty()) {
			int x = q.poll();
			System.out.printf(x+" ");
			for (int t = 0; t < map[x].length; t++) {
				int c = map[x][t]; //현재 정점의 간선 존재여부 판단
				if(c == 1 && !bfsCheck[t]) {
					q.offer(t);
					bfsCheck[t] = true;
				}
			}
		}
		
	}
	static void dfs(int x) {
		if(dfsCheck[x]) return;
		
		dfsCheck[x] = true;
		System.out.print(x+" ");
		
		for(int t=0; t<map[x].length; t++) {
			int c = map[x][t]; //현재 정점의 간선 존재여부 판단
			//간선이 있고 방문한적이 없으면
			if(c == 1 && !dfsCheck[t]) {
				dfs(t);
			}
		}
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String option = br.readLine();
		String[] optionArr = option.split(" ");
		
		int vertexCount = Integer.parseInt(optionArr[0].trim());
		int edgeCount = Integer.parseInt(optionArr[1].trim());
		int index = Integer.parseInt(optionArr[2].trim());
		
		bfsCheck = new boolean[vertexCount+1];
		dfsCheck = new boolean[vertexCount+1];
		map = new int[vertexCount+1][vertexCount+1];
		
		for (int i = 0; i < edgeCount; i++) {	
			String edgeInfo = br.readLine();
			String[] edgeArr = edgeInfo.split(" ");
			int edge1 = Integer.parseInt(edgeArr[0].trim());
			int edge2 = Integer.parseInt(edgeArr[1].trim());

			map[edge1][edge2] = map[edge2][edge1] = 1;
			
		}
		dfs(index);
		System.out.println();
		bfs(index);
	}

}

 

URL :  www.acmicpc.net/problem/1260

반응형

+ Recent posts