https://www.acmicpc.net/problem/16173
16173번: 점프왕 쩰리 (Small)
쩰리는 맨 왼쪽 위의 칸에서 출발해 (행, 열)로 나타낸 좌표계로, (1, 1) -> (2, 1) -> (3, 1) -> (3, 3)으로 이동해 게임에서 승리할 수 있다.
www.acmicpc.net
저는 해당 문제를 DFS를 이용해 문제를 해결하였습니다.
저는 visited 배열을 통해 방문 체크를 하고 해당 좌표에 다시 방문하지 못하도록 하였습니다.
package BOJ.dfs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_16173 {
private static final String SUCCESS = "HaruHaru";
private static final String FAIL = "Hing";
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;
int n = stoi.apply(st.nextToken());
int[][] input = new int[n][n];
for(int i = 0 ; i < n ; i++){
st = new StringTokenizer(br.readLine()," ");
for(int j = 0 ; j < n ; j++){
input[i][j] = stoi.apply(st.nextToken());
}
}
boolean[][] visited = new boolean[n][n];
if(dfs(0,0,input,visited,n)){
System.out.println(SUCCESS);
}else{
System.out.println(FAIL);
}
}
private static final int[] dy = {0,1};
private static final int[] dx = {1,0};
private static final int GOAL = -1;
private static boolean dfs(int y, int x,int[][] input, boolean[][] visited,int n) {
visited[y][x] = true;
if(input[y][x] == GOAL){
return true;
}
int length = input[y][x];
boolean result = false;
for(int i = 0 ; i < 2 ; i++){
int ny = y + length * dy[i];
int nx = x + length * dx[i];
if(checkBound(ny,nx,n) && !visited[ny][nx] && dfs(ny,nx,input,visited,n)){
result = true;
break;
}
}
return result;
}
private static boolean checkBound(int y ,int x, int n){
if(y >= 0 && y < n && x >= 0 && x < n ){
return true;
}
return false;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 쿼드압축 후 개수 세기 (JAVA) (0) | 2022.06.10 |
---|---|
프로그래머스 1차 캐시 (JAVA) (0) | 2022.06.09 |
백준 2234번 성곽 (JAVA) (0) | 2022.06.06 |
프로그래머스 짝지어 제거하기 (JAVA) (0) | 2022.06.05 |
프로그래머스 점프와 순간 이동 (JAVA) (0) | 2022.06.04 |