View
λ°μν
곡ν΅μ½λ (Main)
static int N;
static boolean adjMatrix[][];
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
N = sc.nextInt(); // μ μ μ
int C = sc.nextInt(); // κ°μ μ
adjMatrix = new boolean[N][N]; // 0μΌλ‘ μ΄κΈ°νλ μν
for (int i = 0; i < C; ++i) {
int from = sc.nextInt();
int to = sc.nextInt();
adjMatrix[to][from] = adjMatrix[from][to] = true;
}
bfs();
dfs(0, new boolean[N]);
}
BFS
π‘ μΈμ 리μ€νΈ μ΄μ©
private static void bfs() {
Queue<Integer> queue = new LinkedList<Integer>();
boolean visited[] = new boolean[N];
// 0 μ μ μ μμ μΌλ‘
visited[0] = true; // λ°©λ¬Έμ²λ¦¬
queue.offer(0); // νμ μΆκ°
while (!queue.isEmpty()) {
int cur = queue.poll();
System.out.print((char) (cur + 65));
// ν μ μ μ μΈμ μ μ λ€μ νμ λ£μ΄μ μ°¨ν νμνλλ‘ λ§λ€κΈ°
for (int i = 0; i < N; i++) {
if (adjMatrix[cur][i] && !visited[i]) { // λ°©λ¬Έμ νμ§ μκ³ , νμ¬ μ μ μμ κ·Έ μ μ μΌλ‘ κ° μ μλμ§
visited[i] = true;
queue.offer(i);
}
}
}
System.out.println();
}
DFS
π‘ μ¬κ·λ‘ ꡬν
private static void dfs(int current, boolean[] visited) {
visited[current] = true; //λ°©λ¬Έμ²λ¦¬
System.out.print((char) (current + 65));
for (int i = 0; i < N; ++i) {
if (adjMatrix[current][i] && !visited[i]) {
dfs(i, visited);
}
}
}
}
λ°μν
'μκ³ λ¦¬μ¦' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[Java] μμ΄/μ‘°ν©/λΆλΆμ§ν© (0) | 2022.08.30 |
---|---|
[Java] μμ΄/μ‘°ν©/λΆλΆμ§ν© (0) | 2022.08.30 |
[Java] μ‘°ν© (Combination) (0) | 2022.08.30 |
[Java] μμ΄(permutation) (0) | 2022.08.30 |
[Java] BFS(Breadth First Search) (0) | 2022.08.30 |
reply