본문 바로가기
코딩테스트/코딩테스트(Java)

[코딩테스트] Java - 기본 점검: DFS/BFS

by cogito30 2025. 4. 9.
반응형

1. BFS

더보기
static int N = 5, M = 5;
static int[][] map = new int[N][M];
static boolean[][] visited = new boolean[N][M];
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};

static void bfs(int x, int y) {
    Queue<int[]> queue = new LinkedList<>();
    queue.offer(new int[]{x, y});
    visited[x][y] = true;

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

        for (int i = 0; i < 4; i++) {
            int nx = cx + dx[i];
            int ny = cy + dy[i];

            // 범위 & 방문 체크
            if (nx < 0 || ny < 0 || nx >= N || ny >= M) continue;
            if (visited[nx][ny] || map[nx][ny] == 0) continue;

            visited[nx][ny] = true;
            queue.offer(new int[]{nx, ny});
        }
    }
}

2. DFS

더보기
static int N = 5, M = 5;
static int[][] map = new int[N][M];
static boolean[][] visited = new boolean[N][M];
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};

static void dfs(int x, int y) {
    visited[x][y] = true;

    for (int i = 0; i < 4; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];

        if (nx < 0 || ny < 0 || nx >= N || ny >= M) continue;
        if (visited[nx][ny] || map[nx][ny] == 0) continue;

        dfs(nx, ny);
    }
}

 

반응형