๐ต ThingsILearned
โ๏ธ ์ฌ๊ทํจ์ ๋ฉ์ถ๊ธฐ
ํจ์ ๋ด๋ถ์์ ํจ์๊ฐ ์๊ธฐ ์์ ์ ๋ ๋ค์ ํธ์ถ
์ ๋ฉ์ถ๋ ์ฝ๋
๋ฌดํ์ผ๋ก DFS(3) โถ๏ธ DFS(2) โถ๏ธ DFS(1) โถ๏ธ DFS(0) โถ๏ธ DFS(-1) โถ๏ธ DFS(-2) โถ๏ธ DFS(-3)โฆโฆ
๋ฐ๋ผ์ ์ฌ๊ทํจ์๋ ๋ฌด์กฐ๊ฑด if
, else
, return
์ฌ๊ท๋ฅผ ๋ฉ์ถ๋ ์กฐ๊ฑด์ด ๊ผญ ํ์ํ๋ค
โ ๋ฌดํ ์ฝ๋
1
2
3
| public void DFS(int n){
DFS(n - 1); //์ฌ๊ธฐ๊น์งํ๋ฉด ๋ฌดํ์ผ๋ก ๋๋ค
}
|
โญ๏ธ 3, 2, 1๊น์ง๋ง ์ถ๋ ฅ๋๋ ํจ์
if
, else
, return
์ ์ฌ์ฉํ๋ค.
return
: ๊ฐ์ ๋ฐํํ ์๋ ์์ง๋ง ํจ์ ์ข
๋ฃ์ ์๋ฏธ๋ ๊ฐ์ง๋ค.
1
2
3
4
5
6
| public void DFS(int n){
if(n==0) return; //โญ๏ธ
else {
DFS(n - 1);
}
}
|
โ๏ธ ํจ์์ ์์์ ๋ฐ๋ผ์ ์ถ๋ ฅ ๊ฐ์ด ๋ฌ๋ผ์ง๋ค.
3, 2, 1 ์ถ๋ ฅ
1
2
3
4
5
6
7
| public void DFS(int n){
if(n==0) return;
else {
System.out.print(n+ " ");
DFS(n - 1); //โญ๏ธ
}
}
|
1, 2, 3 ์ถ๋ ฅ
1
2
3
4
5
6
7
| public void DFS(int n){
if(n==0) return;
else {
DFS(n - 1); //โญ๏ธ
System.out.print(n+ " ");
}
}
|
โ๏ธ ์ฌ๊ทํจ์๋ stack frame์ ์ฌ์ฉํ๋ค.
โ ์์ ํจ์์ ์์์ ๋ฐ๋ผ์ ์ถ๋ ฅ ๊ฐ์ด ๋ฌ๋ผ์ง๋ค.
์์ ์ ์์์ ๋ฐ๋ผ ์ถ๋ ฅ๊ฐ์ด ๋ฌ๋ผ์ก์๊น?
์ฌ๊ทํจ์๋ stack frame
์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ด๋ค.
๐ก stack
์ ๊ฐ์ฅ ์๋จ์ ์๋ ๊ฒ์ด ์๋ํ๋ค.
๐ก stack frame
์ ์ฌ์ฉํจ์ผ๋ก ์ธํด์ back tracking
์ ํ ์ ์๋ค.
๐ก stack frame
์ ์ ์ฅ๋๋ ๊ฒ์
โ ๋งค๊ฐ๋ณ์
โโโโโ ์๋ ๊ทธ๋ฆผ์ ์๋ ์ฝ๋์ ๊ฒฝ์ฐ n์ด ๋งค๊ฐ๋ณ์
โ ์ง์ญ๋ณ์
โ ๋ณต๊ท์ฃผ์
โโโโโโ ์๋ฅผ ๋ค์ด DFS(2)
๋ ๋ณต๊ท์ฃผ์๊ฐ DFS(3)
์ผ ๊ฒ์ด๋ค.
โ๏ธ 1, 2, 3์ด ์ถ๋ ฅ๋๋ stack frame ์๋ฆฌ ๊ทธ๋ฆผ์ผ๋ก ์ค๋ช
โ
1๋ถํฐ n๊น์ง ์ถ๋ ฅํ๋ ์ฌ๊ทํจ์๋ฅผ ๋ง๋์ธ์
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| class Main {
public void DFS(int n){
if(n==0) return;
else {
DFS(n - 1);
System.out.print(n+ " ");
}
}
public static void main(String[] args) {
Main T = new Main();
T.DFS(3);
}
}
|
โ
์ญ์ง์๋ฅผ ์ด์ง์๋ก ๋ฐ๊ฟ์ฃผ๋ ์ฌ๊ทํจ์๋ฅผ ๋ง๋์ธ์
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| class Main {
public void DFS(int n){
if(n==0) return;
else {
DFS(n/2);
System.out.print(n%2);
}
}
public static void main(String[] args) {
Main T = new Main();
T.DFS(13);
}
}
|
โ
ํฉํ ๋ฆฌ์ผ์ ๊ตฌํ๋ ์ฌ๊ทํจ์๋ฅผ ๋ง๋์ธ์
1
2
3
4
5
6
7
8
9
10
11
12
13
| class Main {
public int DFS(int n){
if(n==1) return 1;
else {
return n* DFS(n-1);
}
}
public static void main(String[] args) {
Main T = new Main();
System.out.println(T.DFS(5));
}
}
|