yjee0215   1년 전

안녕하세요. 해당 문제를 BFS, DFS, DP 세 방법으로 다 풀어봤는데 궁금한 내용이 있어 질문 남깁니다. 

1. 처음에 BFS로 풀었는데 시간초과가 나서 내부 코드를 변경해보았더니 700ms로 통과가 됐습니다. 이러한 경우 객체를 단순 int형 배열로 변경하여 그에 따른 오버헤드가 줄어 통과가 된 것일까요? 알고리즘을 풀 때에 객체를 사용 오버헤드를 고려해야 하는 지가 궁금합니다. (그전까진 단순히 무시해도 될 정도라고 생각했습니다.)

[기존 BFS 풀이]

import java.util.*;
import java.io.*;

class Point{
    int i;
    int j;

    public Point(int i, int j){
        this.i=i;
        this.j=j;
    }
}

class Pipe{
    Point p1;
    Point p2;
    Dir dir;

    public Pipe(Point p1, Point p2, Dir dir){
        this.p1=p1;
        this.p2=p2;
        this.dir=dir;
    }

    public Pipe createHorizontal(){
        return new Pipe(p2, new Point(p2.i, p2.j+1), Dir.horizontal);
    }

    public Pipe createVertical(){
        return new Pipe(p2, new Point(p2.i+1, p2.j), Dir.vertical);
    }

    public Pipe createDiagonal(){
        return new Pipe(p2, new Point(p2.i+1, p2.j+1), Dir.diagonal);
    }

    public List<Pipe> move(){
        List<Pipe> pipes = new ArrayList<>();
        pipes.add(createDiagonal());

        //가로
        if(dir == Dir.horizontal){
            pipes.add(createHorizontal());
        }

        //세로
        if(dir == Dir.vertical){
            pipes.add(createVertical());
        }

        //대각선
        if(dir == Dir.diagonal){
            pipes.add(createHorizontal());
            pipes.add(createVertical());
        }

        return pipes;
    }
}

enum Dir{
    horizontal, vertical, diagonal;
}

public class Main{
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        int[][] fields = new int[N+1][N+1];

        StringTokenizer st;
        for(int i=1;i<=N;i++){
            st = new StringTokenizer(br.readLine());
            for(int j=1;j<=N;j++){
                fields[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        Pipe start = new Pipe(new Point(1, 1), new Point(1, 2), Dir.horizontal);
        Queue<Pipe> queue = new LinkedList<>();
        queue.add(start);

        int cnt = 0;
        while(!queue.isEmpty()){
            Pipe now = queue.poll();

            if(now.p2.i == N && now.p2.j == N){
                cnt++;
                continue;
            }

            List<Pipe> pipes = now.move();

            for(Pipe pipe:pipes){
                Point checkedPoint = pipe.p2;
                //구간 확인
                if(checkedPoint.i > N || checkedPoint.j > N){
                    continue;
                }

                if(fields[checkedPoint.i][checkedPoint.j] == 1){
                    continue;
                }

                //Diagonal 추가 확인
                if(pipe.dir == Dir.diagonal){
                    if(fields[checkedPoint.i-1][checkedPoint.j] == 1){
                        continue;
                    }

                    if(fields[checkedPoint.i][checkedPoint.j-1] == 1){
                        continue;
                    }
                }

                queue.add(pipe);
            }
        }

        System.out.print(cnt);
    }
}

[변경한 BFS 풀이]

import java.util.*;
import java.io.*;

public class Main {
	static int calculationCnt;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int N = Integer.parseInt(br.readLine());

		int[][] fields = new int[N + 1][N + 1];

		StringTokenizer st;
		for (int i = 1; i <= N; i++) {
			st = new StringTokenizer(br.readLine());
			for (int j = 1; j <= N; j++) {
				fields[i][j] = Integer.parseInt(st.nextToken());
			}
		}

		Queue<int[]> queue = new ArrayDeque<>();
		queue.add(new int[] { 1, 2, 0 }); // 0: 가로 1: 세로 2: 대각선

		int cnt = 0;
		while (!queue.isEmpty()) {
			int[] now = queue.poll();

			if (now[0] == N && now[1] == N) {
				cnt++;
				continue;
			}

			// 가로
			if (now[2] == 0 || now[2] == 2) {
				if (now[1] + 1 <= N && fields[now[0]][now[1] + 1] == 0) {
					queue.add(new int[] { now[0], now[1] + 1, 0 });
				}
			}

			// 세로
			if (now[2] == 1 || now[2] == 2) {
				if (now[0] + 1 <= N && fields[now[0] + 1][now[1]] == 0) {
					queue.add(new int[] { now[0] + 1, now[1], 1 });
				}
			}

			// 대각선
			if (now[0] + 1 <= N && now[1] + 1 <= N && fields[now[0] + 1][now[1] + 1] == 0 && fields[now[0]+1][now[1]] == 0 && fields[now[0]][now[1]+1] == 0) {
				queue.add(new int[] { now[0] + 1, now[1] + 1, 2 });
			}

		}

		System.out.print(cnt);
	}
}

2. DFS와 BFS 모두 연산 수는 같은데 왜 DFS의 시간이 더 적게 나올까요?

아래 두 함수를 돌려도 시간이 크게 차이가 납니다. 제가 생각했을 땐 연산 수도 같고 로직도 동일하며 오히려 스택 프레임을 쌓지 않는 bfs가 더 빨라야 한다고 생각합니다. 

[BFS] 결과: 13, 연산 횟수: 61
589200ns
[DFS] 결과: 13, 연산 횟수: 61
16300ns
몇배인가요?: 36.147239263803684

[bfs 코드]

public static int bfs(int N, int[][] fields) {
        Queue queue = new ArrayDeque<>();
        queue.add(new int[] { 1, 2, 0 }); // 0: 가로 1: 세로 2: 대각선

        int cnt = 0;
        while (!queue.isEmpty()) {
            calculationCnt++;
            int[] now = queue.poll();

            if (now[0] == N && now[1] == N) {
                cnt++;
                continue;
            }

            // 가로
            if (now[2] == 0 || now[2] == 2) {
                if (now[1] + 1 <= N && fields[now[0]][now[1] + 1] == 0) {
                    queue.add(new int[] { now[0], now[1] + 1, 0 });
                }
            }

            // 세로
            if (now[2] == 1 || now[2] == 2) {
                if (now[0] + 1 <= N && fields[now[0] + 1][now[1]] == 0) {
                    queue.add(new int[] { now[0] + 1, now[1], 1 });
                }
            }

            // 대각선
            if (now[0] + 1 <= N && now[1] + 1 <= N && fields[now[0] + 1][now[1] + 1] == 0
                    && fields[now[0] + 1][now[1]] == 0 && fields[now[0]][now[1] + 1] == 0) {
                queue.add(new int[] { now[0] + 1, now[1] + 1, 2 });
            }

        }

        return cnt;
    }

[dfs 코드]

public static int dfs(int i, int j, int dir, int N, int[][] fields) {
        calculationCnt++;
        // 목표 지점에 도달한 경우
        if (i == N && j == N) {
            return 1;
        }

        int sum = 0;

        // 가로 방향 이동
        if (dir == 0 || dir == 2) {
            if (j + 1 <= N && fields[i][j + 1] == 0) {
                sum += dfs(i, j + 1, 0, N, fields);
            }
        }

        // 세로 방향 이동
        if (dir == 1 || dir == 2) {
            if (i + 1 <= N && fields[i + 1][j] == 0) {
                sum += dfs(i + 1, j, 1, N, fields);
            }
        }

        // 대각선 방향 이동
        if (i + 1 <= N && j + 1 <= N && fields[i][j + 1] == 0 && fields[i + 1][j] == 0 && fields[i + 1][j + 1] == 0) {
            sum += dfs(i + 1, j + 1, 2, N, fields);
        }

        return sum;
    }

3. 제가 구현한 bfs 코드는 실제 깊이 우선 탐색이 아닐까요?
질문 내용 중 bfs와 bfs처럼 구현된 brute-force 코드는 다른 것이라는 말씀이 있었는데, 현재 문제에서는 방문 배열을 추가하면 최종 (N,N)에 도달하는 경우를 셀 수 없어서 방문 배열을 추가하지 않았습니다. 그렇다면 이 코드는 깊이 우선 탐색 코드가 아닌 걸까요?

긴 내용 읽어주셔서 감사합니다!

댓글을 작성하려면 로그인해야 합니다.