-
카테고리
-
세부 분야
알고리즘 · 자료구조
-
해결 여부
미해결
1012 - 반례를 모르겠습니다. JAVA
23.06.05 15:10 작성 조회수 187
0
안녕하세요. 큰돌님 강의 잘 보고있습니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
static int[][] board;
static boolean[][] visited;
static int[] dy = {-1, 0, 1, 0};
static int[] dx = {0, 1, 0, -1};
static int yLen;
static int xLen;
static int cnt;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
while (n-- > 0) {
int[] given = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
if (given[2] == 1) {
sb.append(1).append(System.lineSeparator());
continue;
}
board = new int[given[0]][given[1]];
visited = new boolean[given[0]][given[1]];
yLen = given[0];
xLen = given[1];
for (int i = 0; i < given[2]; i++) {
String[] numStr = br.readLine().split(" ");
int y = Integer.parseInt(numStr[0]);
int x = Integer.parseInt(numStr[1]);
board[y][x] = 1;
}
for (int i = 0; i < yLen; i++) {
for (int j = 0; j < xLen; j++) {
if (!visited[i][j] && board[i][j] == 1) {
dfs(i, j);
cnt++;
}
}
}
sb.append(cnt).append(System.lineSeparator());
}
System.out.print(sb.substring(0, sb.length() - 1));
}
public static void dfs(int y, int x) {
visited[y][x] = true;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || ny >= yLen || nx < 0 || nx >= xLen) continue;
if (visited[ny][nx] || board[ny][nx] == 0) continue;
dfs(ny, nx);
}
}
}
위 코드를 실행하면 12%, ArrayIndexOutOfBounds가 발생하는데 어떤 부분인지 알 수 있을까요?
답변을 작성해보세요.
0
최찬호
질문자2023.06.05
if (given[2] == 1) {
sb.append(1).append(System.lineSeparator());
continue;
}
이 코드 때문에 이후에 주어지는 입력값을 읽어오지 않아서 이상한 동작이 되었습니다.. 하하
답변 2