728x90
사다리타기에 따라 정답으로 이어지는 시작점을 찾는 문제다.
정답에서부터 위로 올라가는 방식으로 구현하면 된다.
먼저 목적지의 row, col 좌표를 변수에 설정하고, 오른쪽이나 왼쪽 그리고 위로 올라가도록 구현한다.
이때 주의할 점은
- 위로 가는 것보다 오른쪽 왼쪽이 1인지를 먼저 검사해야 한다.
- 오른쪽, 왼쪽으로 가고 있다면 반대방향으로 돌아가서는 안된다.
이때 2를 고려하지 않아서 무한루프에 빠지는 문제가 발생했다.
그래서 dir 변수를 지정해줘서 오른쪽, 왼쪽으로 가는 경우는 반대방향이 아닐 경우에만 이동하도록 설정하였다.
package SWEA0811;
import java.util.Scanner;
public class SWEA_1210_Ladder {
static int[][] ladder = new int[100][100];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int t = 0; t < 10; t++) {
int T = sc.nextInt();
int xr = 0;
int xc = 0;
for (int i = 0; i < 100; i++)
for (int j = 0; j < 100; j++) {
ladder[i][j] = sc.nextInt();
if (ladder[i][j] == 2) {
xr = i;
xc = j;
}
}
int dir = 3; // dir 확인
// 1은 왼쪽, 2는 오른쪽, 3은 위
while (xr > 0) { // xc가 0이 되면 그때 xr 값이 구하려는 값
if (xc - 1 >= 0 && ladder[xr][xc - 1] == 1 && dir != 2) {
dir = 1;
xc--;
}
else if (xc + 1 < 100 && ladder[xr][xc + 1] == 1 && dir != 1) {
dir = 2;
xc++;
} else if (ladder[xr - 1][xc] == 1) {
dir = 3;
xr--;
}
}
System.out.println("#" + T + " " + xc);
}
}
}
728x90
'문제 풀이 > SWEA' 카테고리의 다른 글
[SWEA] 1873 - 상호의 배틀 필드 (자바/Java) (0) | 2022.08.22 |
---|---|
[SWEA] 1216 - 회문 2 (자바/Java) (0) | 2022.08.12 |
[SWEA] 5432 - 쇠막대기 자르기 (자바/Java) (0) | 2022.08.11 |
[SWEA] 6190 - 정곤이의 단조 증가하는 수 (자바/Java) (0) | 2022.08.11 |
[SWEA] 1954 - 달팽이 숫자 (자바/Java) (0) | 2022.08.10 |