설명

도착점까지 갈 수 있는 방법의 수는 몇가지 인가?

 

 

예시

0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 0 0 1 0 0 0
1 1 0 1 0 1 1
1 1 0 0 0 0 1
1 1 0 1 1 0 0
1 0 0 0 0 0 0

 

8

 

 

 

 

풀이

처음에 1로 막아두고 dfs 돌고난다음에는 0으로 다시 해제해주어야한다.

import java.util.*;
class Main {
	static int ans;
	static int [][] board = new int[8][8];
	
	static int [] dx= {0,1,0,-1};
	static int [] dy= {-1,0,1,0};
	
	public void DFS(int x, int y) {
		
		if(x==7 && y==7) {
			ans++;
		}else {
			for(int i=0; i<4; i++) {
				int nx= x+dx[i];
				int ny= y+dy[i];
				
				if(nx>=1&& ny>=1 && nx<=7 && 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 sc = new Scanner(System.in);
		
		for(int i=1; i<=7; i++) {
			for(int j=1; j<=7; j++) {
				board[i][j]=sc.nextInt();
			}
		}

		board[1][1]=1;
		T.DFS(1,1);
		System.out.println(ans);
	}	
}

 

'알고리즘기초 > DFS,BFS활용' 카테고리의 다른 글

12. 토마토(BFS 활용)  (0) 2022.10.01
11. 미로의 최단거리 통로(BFS)  (1) 2022.10.01
09. 조합구하기  (1) 2022.09.30
08. 수열 추측  (1) 2022.09.30
07. 조합의 경우수(메모이제이션)  (0) 2022.09.29

+ Recent posts