[์ธํ๋ฐ/DFS/10.๋ฏธ๋กํ์]
<<ํ์ด>>
์ด ๋ฌธ์ ๋ ch์ DFS ๊ทธ๋ฆฌ๊ณ dx, dy๋ฅผ ์ ์ ์ฉํ๋ฉด ์ฝ๊ฒ ํ ์ ์๋ ๋ฌธ์ ์ด๋ค.
์ฐ์ ์ ์ฌ๊ธฐ์ 1,1 ์ ์ด ์์์ด๋ผ๊ณ ํ์ผ๋๊น, ๋ฐฐ์ด ํน์ฑ์ 0,0 ๋ถํฐ ์๊ธฐ๋ ๊ฒ์ ๊ฐ์ํด์ ๊ฐ๋ ์ฑ์ ์ํด 8,8 ๋ก ํฌ๊ธฐ๋ฅผ ๋ง์ถฐ์คฌ๋ค.
์ด๋ ๊ฒ ํ๋ฉด 0ํ 0์ด ์ ๋ถ ์ด์ฉ์ ์ํ๊ณ 1,1๋ถํฐ ์์ํ๊ฒ ํ ์ ์๋ค.
๊ทธ๋ฌ๊ณ ๋ ๋ค์ ์ ์ ํ๊ฒ DFS๋ฅผ ๋ง๋ค์ด์ฃผ๊ณ 7x7 ํ๋ ฌ์์ ๋ฒ์ด๋๋ ๊ฒฝ์ฐ๋ return ํ๋๋ก ํ๋ค.
๋ง์ง๋ง์ผ๋ก ch๋ฅผ ๋ ์ผ๋ก์จ ์ด๋ฏธ ์ง๋๊ฐ ์๋ฆฌ๋ ๋ค์ ํ ๋ฒ ๋์๊ฐ์ง ๋ชปํ๊ฒ ํ๊ธฐ์ํด ch๋ฅผ ๋์ ํ๋ค. ๊ทธ ์ง์ ์ ์ง๋ ๋ ch = 1์ ๋๊ณ ์ ์ง๋๊ฐ๋ฉด ch = 0์ผ๋ก ๋ง๋ค์ด์ฃผ์๋ค.
๊ทธ ๊ฒฐ๊ณผ ์ด์์์ด ๋ฌธ์ ๋ฅผ ํ ์ ์์๋ค !!
์ ํ์ ์ธ DFS ๋ฌธ์ ๋ก์ ์ด์ ์ด๋ฐ ๋ฌธ์ ๋ ์์ฝ๊ฒ ํ ์ ์๋ค ใ ใ
import java.util.Scanner;
class Main {
public static int[] dx = {0, 0, -1, 1};
public static int[] dy = {-1, 1, 0, 0};
public static int count = 0;
public static int[][] ch = new int[8][8];
private void DFS(int[][] arr, int row, int column) {
if (row == 7 && column == 7) {
count++;
return;
}
if (row < 1 || row > 7 || column < 1 || column > 7) {
return;
} else if(ch[row][column] != 1 && arr[row][column] == 0){
ch[row][column] = 1;
DFS(arr, row + dx[0], column + dy[0]);
DFS(arr, row + dx[1], column + dy[1]);
DFS(arr, row + dx[2], column + dy[2]);
DFS(arr, row + dx[3], column + dy[3]);
ch[row][column] = 0;
}
}
public static void main(String[] args) throws Exception{
Main T = new Main();
Scanner in = new Scanner(System.in);
int[][] arr = new int[8][8];
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= 7; j++) {
arr[i][j] = in.nextInt();
}
}
T.DFS(arr, 1, 1);
System.out.println(count);
}
}
-๊ฐ์ฌ๋ ํ์ด-
์ด๋ฒ์๋ ๊ฐ์ฌ๋๊ณผ ๋์ ํ์ด๊ฐ ํฌ๊ฒ ํ๋ฆฌ์ง ์๋ค. ๋ค๋ง, ๋ฐ๋ณต๋ฌธ์ ํ์ฉํด์ ์กฐ๊ธ ๋ ์ฝ๋๋ฅผ ๊น๋ํ๊ฒ ๋ง๋ค์๋ค๋ ์ ์ด๋ค.
for๋ฌธ์ ํตํด DFS์ ์ ์ฐจ์ด๊ฐ ๋๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
๊ทธ๋ฆฌ๊ณ board ์ญ์ static์ผ๋ก ๋นผ์คฌ๋๋ฐ ์ด๋ ๊ฒ๋ ํ ์ ์์์ ํ ๋ฒ ์ธ์งํ๊ณ ๊ฐ๋ค !!
์ธ์๋ ๋์ผํ๋ค ใ ใ
๊ฐ์ฌ๋๊ป ๋ง์ด ๋ฐฐ์์ ๊ทธ๋ฐ์ง ํ์ด ๋ง์ด ๋ฎ์์๋ค !!
์ค๋๋ ๋ง์ด ๋ฐฐ์๊ฐ๋ต
import java.util.*;
class Main {
static int[] dx={-1, 0, 1, 0};
static int[] dy={0, 1, 0, -1};
static int[][] board;
static int answer=0;
public void DFS(int x, int y){
if(x==7 && y==7) answer++;
else{
for(int i=0; i<4; i++){
int nx=x+dx[i];
int ny=y+dy[i];
if(nx>=1 && nx<=7 && ny>=1 && ny<=7 && board[nx][ny]==0){
board[nx][ny]=1;
DFS(nx, ny);
board[nx][ny]=0;
}
}
}
}
public static void main(String[] args){
Main T = new Main();
Scanner kb = new Scanner(System.in);
board=new int[8][8];
for(int i=1; i<=7; i++){
for(int j=1; j<=7; j++){
board[i][j]=kb.nextInt();
}
}
board[1][1]=1;
T.DFS(1, 1);
System.out.print(answer);
}
}
'์ฝ๋ฉํ ์คํธ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์ธํ๋ฐ/BFS/11. ๋ฏธ๋ก์ ์ต๋จ๊ฑฐ๋ฆฌ ํต๋ก] (0) | 2024.04.09 |
---|---|
[๋ฐฑ์ค/1015/์์ด ์ ๋ ฌ] (1) | 2024.04.06 |
[์ธํ๋ฐ/DFS/9.์กฐํฉ๊ตฌํ๊ธฐ] - ์ ๋ฆฌ ์ค - (0) | 2024.03.26 |
[๋ฐฑ์ค/1271/์์ฒญ๋ ๋ถ์2] (0) | 2024.03.26 |
[๋ฐฑ์ค/1076/์ ํญ] (0) | 2024.03.26 |
๋๊ธ