Baekjun online jersey is solving a problem, but there is no answer... There is no error when coding with C, but if (arr[x][y-1] == 1 &&y-1 > = 0) line gives java.lang.ArrayIndexOutOfBoundsException error... I know why it flies, but I don't know how to solve it.
Masters, please answer.
package baekjun;
import java.util.Scanner;
public class problem6{
static int M,N,K;
static int[][] arr;
static int[][] visited;
static int testcase;
public static void main(String[] args){
int myX = 0;
int myY = 0;
Scanner sc = new Scanner(System.in);
testcase = sc.nextInt();
M = sc.nextInt();
N = sc.nextInt();
K = sc.nextInt();
arr = new int[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
arr[i][j] = 0;
}
}
for(int k = 0; k<testcase; k++) {
int count = 0;
for (int i = 0; i < K; i++){
myX = sc.nextInt();
myY = sc.nextInt();
arr[myX][myY] = 1;
}
for(int i = 0; i<M; i++) {
for (int j = 0; j<N; j++) {
if(arr[i][j] == 1) {
DFS(i, j);
count++;
}
}
}
System.out.println(count);
}
}
static void DFS(int x, int y){
arr[x][y] = 0;
if(arr[x+1][y] == 1 && x+1 < M)
DFS(x+1, y);
if(arr[x][y+1] == 1 && y+1 < N)
DFS(x, y+1);
if(arr[x-1][y] == 1 && x-1 >= 0)
DFS(x-1, y);
if(arr[x][y-1] == 1 && y-1 >= 0)
DFS(x, y-1);
}
}
}
if(arr[x][y-1] == 1 && y-1 >= 0)
if(y-1 >= 0 && arr[x][y-1] == 1)
Change it to .
You don't do logical operations at the same time, you do them one by one from the first sentence. Executing the following statements follows:
© 2024 OneMinuteCode. All rights reserved.