알고리즘

백준 17070번 파이프 옮기기1 (JAVA)

박카스마시며코딩 2021. 12. 22. 16:24

https://www.acmicpc.net/problem/17070

 

17070번: 파이프 옮기기 1

유현이가 새 집으로 이사했다. 새 집의 크기는 N×N의 격자판으로 나타낼 수 있고, 1×1크기의 정사각형 칸으로 나누어져 있다. 각각의 칸은 (r, c)로 나타낼 수 있다. 여기서 r은 행의 번호, c는 열의

www.acmicpc.net

 

저는 해당 문제를 DP를 적용하여 문제를 해결하였습니다. dp[y][x][현재 방향]에 대한 경로 값을 저장하였습니다.

마지막으로 대각선 방향일 때는 (y,x-1) , (y-1,x)가 0인지를 확인하였습니다.

package BOJ.DP;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_17070 {
    static  int n;
    static int map[][];
    static int dp[][][];
    static int dy[] = {0,1,1};
    static int dx[] = {1,1,0};
    static int dfs(int y , int x,int dir){
//        System.out.printf("%d %d %d \n",y,x,dir);
        if(y == n-1 && x == n-1){
            return 1;
        }
        if(dp[y][x][dir] != -1){
            return dp[y][x][dir];
        }else{
            int result = 0;
            for(int i = -1 ; i <= 1; i++){
                int ndir = dir + i;
                if(ndir >= 0 && ndir <= 2){
                    int ny = y + dy[ndir];
                    int nx = x + dx[ndir];
                    if(ny >= 0 && ny < n && nx >= 0 && nx < n && map[ny][nx] == 0){
                        if(ndir == 1 && (map[ny-1][nx] != 0 || map[ny][nx-1] != 0)){
                            continue;
                        }
                        result += dfs(ny,nx,ndir);
                    }
                }
            }
            dp[y][x][dir] = result;
            return result;
        }
    }
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        Function<String,Integer> stoi = Integer::parseInt;
        n = stoi.apply(st.nextToken());
        map = new int[n][n];
        dp = new int[n][n][3];
        for(int i = 0 ; i  < n ; i++){
            st = new StringTokenizer(br.readLine()," ");
            for(int j = 0 ; j < n ; j++){
                map[i][j] = stoi.apply(st.nextToken());
                Arrays.fill(dp[i][j],-1);
            }
        }
        System.out.println(dfs(0,1,0));
    }
}