π·πΌλͺ¨μ¬λ΄μ κ°λ°μμ²π·πΌ
[JAVA/μ½λ©ν μ€νΈ] μ‘μμ§ μ°ΎκΈ° (BFS : μννΈλ¦¬νμ) λ³Έλ¬Έ
[JAVA/μ½λ©ν μ€νΈ] μ‘μμ§ μ°ΎκΈ° (BFS : μννΈλ¦¬νμ)
μμΌμ΄ 2021. 8. 1. 15:54μ€λͺ
νμλ μ‘μμ§λ₯Ό μμ΄λ²λ Έλ€. λ€νν μ‘μμ§μλ μμΉμΆμ κΈ°κ° λ¬λ € μλ€.
νμμ μμΉμ μ‘μμ§μ μμΉκ° μμ§μ μμ μ’ν μ μΌλ‘ μ£Όμ΄μ§λ©΄ νμλ νμ¬ μμΉμμ μ‘μμ§μ μμΉκΉμ§ λ€μκ³Ό κ°μ λ°©λ²μΌλ‘ μ΄λνλ€.
μ‘μμ§λ μμ§μ΄μ§ μκ³ μ μ리μ μλ€.
νμλ μ€μΉ΄μ΄ 콩콩μ νκ³ κ°λλ° ν λ²μ μ νλ‘ μμΌλ‘ 1, λ€λ‘ 1, μμΌλ‘ 5λ₯Ό μ΄λν μ μλ€.
μ΅μ λͺ λ²μ μ νλ‘ νμκ° μ‘μμ§μ μμΉκΉμ§ κ° μ μλμ§ κ΅¬νλ νλ‘κ·Έλ¨μ μμ±νμΈμ.
μ λ ₯
첫 λ²μ§Έ μ€μ νμμ μμΉ Sμ μ‘μμ§μ μμΉ Eκ° μ£Όμ΄μ§λ€. μ§μ μ μ’ν μ μ 1λΆν° 10,000κΉμ§μ΄λ€.
μΆλ ₯
μ νμ μ΅μνμλ₯Ό ꡬνλ€. λ΅μ 1μ΄μμ΄λ©° λ°λμ μ‘΄μ¬ν©λλ€.
μμ μ λ ₯ 1
5 14
μμ μΆλ ₯ 1
3
- 2022.01.25 νμ΄
import java.util.*;
public class Main {
public static void solution(int S, int E) {
// κ²°κ³Όκ°
int result = 1;
Queue<Integer> Q = new LinkedList<>();
// μ€λ³΅λ°©μ§λ₯Ό μν arrayList
ArrayList<Integer> arrayList = new ArrayList();
Q.offer(S);
while(!Q.isEmpty()){
int len = Q.size();
for(int i=0; i<len; i++){
int compare = Q.poll();
if(compare+1 == E || compare+5 == E || compare-1 == E){
System.out.println(result);
return;
}
// μ€λ³΅λ°©μ§
if(!arrayList.contains(compare+1)){
Q.offer(compare+1);
arrayList.add(compare+1);
}
if(!arrayList.contains(compare+5)){
Q.offer(compare+5);
arrayList.add(compare+5);
}
if(!arrayList.contains(compare-1)){
Q.offer(compare-1);
arrayList.add(compare-1);
}
}
result++;
}
}
public static void main(String[] args) {
Main main = new Main();
Scanner kb = new Scanner(System.in);
// νμμ μμΉ
int S = kb.nextInt();
// μ‘μμ§μ μμΉ
int E = kb.nextInt();
main.solution(S, E);
}
}
- μ½λ
import java.util.*;
class Main{
int answer = 0;
int[] dis= {1, -1, 5};
// νλ² λ°©λ¬Έ νλκ²μ μ μ₯ - μκ°λ³΅μ‘λ μ€μ΄κΈ° μν¨
int[] ch;
Queue<Integer> Q = new LinkedList<>();
public int BFS(int s, int e) {
ch = new int[10001];
ch[s] = 1;
Q.offer(s);
int Level = 0;
while(!Q.isEmpty()) {
int len=Q.size();
for(int i=0; i<len; i++) {
int x = Q.poll();
// λ°©λ² 1
//if(x==e) {
// return Level;
//}
for(int j=0; j<3; j++) {
int nx = x+dis[j];
// λ°©λ² 2
if(nx==e) {
return Level + 1;
}
// λ°©λ¬Έ μνκ±°
if(nx >=1 && nx<=10000 && ch[nx] == 0) {
ch[nx] = 1;
Q.offer(nx);
}
}
}
Level ++;
}
return Level;
}
public static void main(String[] args) {
Main T = new Main();
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int e = in.nextInt();
System.out.println(T.BFS(s, e));
}
}
'κ°λ° > μκ³ λ¦¬μ¦ λ¬Έμ νμ΄ JAVA' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
κ·Έλνμ μΈμ νλ ¬ (0) | 2021.08.01 |
---|---|
Tree λ§λ¨λ ΈλκΉμ§μ κ°μ₯ 짧μ κ²½λ‘(DFS, BFS) (0) | 2021.08.01 |
μ΄μ§νΈλ¦¬μν : λμ΄μ°μ νμ - λ 벨νμ(BFS : Breadth-First Search) (0) | 2021.07.30 |
λΆλΆμ§ν© ꡬνκΈ°(DFS) (0) | 2021.07.29 |
μ΄μ§νΈλ¦¬μν : κΉμ΄μ°μ νμ(DFS : Depth-fist Search) (0) | 2021.07.27 |