๐ท๐ผ๋ชจ์ฌ๋ด์ ๊ฐ๋ฐ์์ฒ๐ท๐ผ
์ด์งํธ๋ฆฌ์ํ : ๋์ด์ฐ์ ํ์ - ๋ ๋ฒจํ์(BFS : Breadth-First Search) ๋ณธ๋ฌธ
๊ฐ๋ฐ/์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด JAVA
์ด์งํธ๋ฆฌ์ํ : ๋์ด์ฐ์ ํ์ - ๋ ๋ฒจํ์(BFS : Breadth-First Search)
์์ผ์ด 2021. 7. 30. 11:50๋ฐ์ํ
Stack์ ์ฌ์ฉํ๋ DFS(๊น์ด์ฐ์ ํ์)๊ณผ ๋ค๋ฅด๊ฒ BFS(๋์ด์ฐ์ ํ์)์ Queue๋ฅผ ์ฌ์ฉํ๋ฉฐ ๊ฐ ๋ ธ๋ ์์น์๋ฐ๋ผ Level์ ์ ํ์ฌ ํ์ํ๋ค.
import java.util.*;
class Node{
int data;
Node lt, rt;
public Node(int val) {
data = val;
lt = rt = null;
}
}
public class Main{
Node root;
public void BFS(Node root) {
Queue<Node> Q = new LinkedList<>();
Q.offer(root);
int Level = 0;
while(!Q.isEmpty()) {
int len = Q.size();
System.out.print(Level + " : ");
for(int i=0; i<len; i++) {
Node cur = Q.poll();
System.out.print(cur.data + " ");
if(cur.lt!=null) {
Q.offer(cur.lt);
}
if(cur.rt != null) {
Q.offer(cur.rt);
}
}
Level++;
System.out.println();
}
}
public static void main(String args[]) {
Main tree = new Main();
tree.root = new Node(1);
tree.root.lt = new Node(2);
tree.root.rt = new Node(3);
tree.root.lt.lt = new Node(4);
tree.root.lt.rt = new Node(5);
tree.root.rt.lt = new Node(6);
tree.root.rt.rt = new Node(7);
tree.BFS(tree.root);
}
}
'๊ฐ๋ฐ > ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด JAVA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Tree ๋ง๋จ๋ ธ๋๊น์ง์ ๊ฐ์ฅ ์งง์ ๊ฒฝ๋ก(DFS, BFS) (0) | 2021.08.01 |
---|---|
[JAVA/์ฝ๋ฉํ ์คํธ] ์ก์์ง ์ฐพ๊ธฐ (BFS : ์ํํธ๋ฆฌํ์) (0) | 2021.08.01 |
๋ถ๋ถ์งํฉ ๊ตฌํ๊ธฐ(DFS) (0) | 2021.07.29 |
์ด์งํธ๋ฆฌ์ํ : ๊น์ด์ฐ์ ํ์(DFS : Depth-fist Search) (0) | 2021.07.27 |
[JAVA/์ฝ๋ฉํ ์คํธ] ํผ๋ณด๋์น ์์ด(๋ฉ๋ชจ์ด์ ์ด์ ) (0) | 2021.07.13 |
Comments