반응형
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);
}
}
반응형
'코딩테스트 > 코딩테스트(Java)' 카테고리의 다른 글
[코딩테스트] Java - 순열/조합 추천 문제 (0) | 2025.04.09 |
---|---|
[코딩테스트] Java - 기본 점검: 순열/조합 (0) | 2025.04.09 |
[코딩테스트] Java - 기본 점검: 입출력 (0) | 2025.04.09 |
[코딩테스트] Java - 기본 점검: 주요 메서드 (0) | 2025.04.09 |
[코딩테스트] Java - 기본 점검: 정렬 (0) | 2025.04.09 |