π‘BFS
BFSλ λλΉ μ°μ νμμΌλ‘, λ£¨νΈ λ Έλμμ νμμ μμνμ¬ κ°μ λ 벨μ μλ λ Έλλ₯Ό λͺ¨λ νμν λ€μ
νμ λ λ²¨λ‘ λ΄λ €κ° λ λͺ¨λ νμμ μ§ννλ€κ°, λ μ΄μ νμν λ Έλκ° μμ λ νμμ λ©μΆλ λ°©μμΌλ‘ λμνλ€.
νλ₯Ό μ΄μ©νμ¬ κ΅¬ννλ€.
π‘ BFS μ½λꡬν
import java.util.*;
class Node{
int data;
Node lt,rt;
public Node(int val){
data=val;
lt=rt=null;
}
}
public class Solution {
Node root;
public void BFS(Node root) {
Queue<Node> Q=new LinkedList<>();
Q.offer(root);
int L=0;
while(!Q.isEmpty()){
int len=Q.size();
System.out.print(L+" : ");
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);
}
L++;
System.out.println();
}
}
public static void main(String[] args) {
Solution tree=new Solution();
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);
}
}
π‘ BFS μ‘μμ§ λ¬Έμ
import java.util.*;
public class Solution {
int[] dis={1,-1,5};
int[] ch; // μ΄λ―Έ μλ κ°μΈμ§ check ν λ°°μ΄
Queue<Integer> Q=new LinkedList<>(); // μ μ Q μ μΈ
public int BFS(int s, int e){ // s = μΆλ°μ / e = λμ°©μ§μ
ch=new int[10001];
ch[s]=1;
Q.offer(s);
int L=0; // root node level = 0
while(!Q.isEmpty()){
int len=Q.size(); // λ 벨μ κΈΈμ΄
for(int i=0; i<len; i++){
int x=Q.poll();
if(x==e) return L;
for(int j=0; j<3; j++){
int nx=x+dis[j]; // nx : μμ node
if(nx>0 && nx<=10000 && ch[nx]==0){ // ch[nx]==0μ΄λ©΄ λ°©λ¬Έ X
ch[nx]=1; // λ°©λ¬Ένλ€κ³ check
Q.offer(nx);
}
}
}
L++; // level μ¦κ°
}
return 0;
}
public static void main(String[] args) {
Solution T = new Solution();
Scanner kb=new Scanner(System.in);
int s=kb.nextInt();
int e=kb.nextInt();
System.out.println(T.BFS(s,e));
}
}
π‘DFS, BFSλ₯Ό νμ©νλ©΄ μ’μ μν©
1. κ·Έλνμ λͺ¨λ μ μ μ λ°©λ¬Ένλ κ²μ΄ μ£Όμν λ¬Έμ : DFS, BFS λͺ¨λ 무방
2. κ²½λ‘μ νΉμ§μ μ μ₯ν΄λ¬μΌ νλ λ¬Έμ : κ° μ μ μ μ«μκ° μκ³ a λΆν° b κΉμ§ κ°λ κ²½λ‘λ₯Ό ꡬνλλ° κ°μ μ«μκ° μμΌλ©΄ μλλ€λ λ¬Έμ λ±, κ°κ°μ κ²½λ‘λ§λ€ νΉμ§μ μ μ₯ν΄λ¬μΌ νλ κ²½μ°λ DFSλ₯Ό μ¬μ©ν΄μΌ νλ€.
BFSλ κ²½λ‘μ νΉμ§μ μ μ₯νμ§ λͺ»νλ€.
3. μ΅λ¨κ±°λ¦¬λ₯Ό ꡬνλ λ¬Έμ : BFSκ° μ 리νλ€. DFSμ κ²½μ° μ²μμΌλ‘ λ°κ²¬λλ ν΄λ΅μ΄ μ΅λ¨κ±°λ¦¬κ° μλ μ μμ§λ§, BFSμ κ²½μ° λ¨Όμ μ°Ύμμ§λ ν΄λ΅μ΄ 곧 μ΅λ¨κ±°λ¦¬μ΄κΈ° λλ¬Έμ΄λ€.
'π μ½λ©ν μ€νΈ > JAVA' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[JAVA] split() μΈμ μ¬λ¬κ° (0) | 2022.12.26 |
---|---|
[JAVA] Collection ( HashMap , HashSet μ°¨μ΄ ) (0) | 2022.11.11 |
[JAVA][μκ³ λ¦¬μ¦] μ λ ¬ μκ³ λ¦¬μ¦ ( μ ν μ½μ λ²λΈ ) (0) | 2022.11.07 |
[JAVA] Queue μ 리 (0) | 2022.11.05 |
[JAVA] Stack μ 리 (0) | 2022.11.05 |