작성
·
246
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가 발생하는데 어떤 부분인지 알 수 있을까요?
답글 감사합니다. 다음에는 c++로 질문 드리도록 하겠습니다.!