Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 항해솔직후기
- SSAFY
- 자바
- 그리디
- 코딩테스트
- DFS
- Union Find
- 알고리즘
- 코테
- BFS
- 코드트리
- 항해플러스ai
- database
- 항해플러스ai후기
- 다시보기
- 코딩테스트실력진단
- JUnit
- 완전탐색
- 그래프
- Java
- 다익스트라
- 알고리즘기본개념
- SWEA
- 유니온파인드
- JPA
- 백준
- 트러블슈팅
- Spring
- 싸피
- DP
Archives
- Today
- Total
HwangHub
[DFS/자바] 코드트리 실력진단. 나이트 본문
문제는 비공개이기 때문에 첨부하지 않겠다.
문제 해석
이 문제는 체스 나이트의 이동 패턴을 이용하여 나이트가 어디어디 갈 수 있는지 파악하는 문제였다. 2차원 격자 위에서 움직이는 패턴이 일정하므로 인접한 좌표로 이동할 수 있는 그래프 탐색 알고리즘을 사용하면 될 것이라고 생각했고, 전체를 탐색해야 하는 것이지 최단거리를 알아낼 필요는 없으므로 상대적으로 구현이 더 단순한 DFS를 사용하는 것이 효율적일 것이라고 판단하였다.
문제에서 요구하는 출력 결과는 visited 배열값을 이용하면 파악할 수 있을 것이라고 판단하였다.
문제 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
private static int n;
private static int[][] arr;
private static boolean[][] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
arr = new int[n][n];
visited = new boolean[n][n];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
st = new StringTokenizer(br.readLine());
int startY = Integer.parseInt(st.nextToken())-1;
int startX = Integer.parseInt(st.nextToken())-1;
visited[startY][startX] = true;
dfs(new Pair(startY, startX));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == 1) {
System.out.print(0 + " ");
} else if (visited[i][j]) {
System.out.print(1 + " ");
} else {
System.out.print(0 + " ");
}
}
System.out.println();
}
}
private static void dfs(Pair crt) {
int[] dx = new int[]{1, 2, 2, 1, -1, -2, -2, -1};
int[] dy = new int[]{-2, -1, 1, 2, 2, 1, -1, -2};
for (int i = 0; i < 8; i++) {
int newY = crt.y + dy[i];
int newX = crt.x + dx[i];
if (canGo(newY, newX)) {
visited[newY][newX] = true;
dfs(new Pair(newY, newX));
}
}
}
private static boolean canGo(int y, int x) {
return inRange(y, x) && arr[y][x] == 0 && !visited[y][x];
}
private static boolean inRange(int y, int x) {
return y >= 0 && y < n && x >= 0 && x < n;
}
private static class Pair {
private int x, y;
private Pair(int y, int x) {
this.x = x;
this.y = y;
}
}
}
'workspace > algorithm' 카테고리의 다른 글
[DP/자바] 코드트리 IL. 사각형 채우기 (0) | 2023.10.19 |
---|---|
[DP/자바] 코드트리 IL.계단 오르기 (0) | 2023.10.18 |
[DFS/자바] 코드트리 IL. 뿌요뿌요 (0) | 2023.10.14 |
[BFS/자바] 코드트리 IL. 상한 귤 (0) | 2023.10.14 |
[BFS/자바] 코드트리 IL. 비를피하기 (0) | 2023.10.13 |
Comments