I added some stuff and executed it.
The Code
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static int matching(char[][] array, boolean[][] check, int n, int m, int x, int y ){
System.err.println(x + " " + y);
if( array[x][y] == '0' || check[x][y] == true ){
check[x][y] = true;
return 0;
}
int sum = 1;
check[x][y] = true;
if( x-1 >= 0 ){ sum += matching(array,check, n, m, x-1, y); }
if( x+1 < m ){ sum += matching(array,check, n, m, x+1, y); }
if( y-1 >= 0 ){ sum += matching(array,check, n, m, x, y-1); }
if( y+1 < n ){ sum += matching(array,check, n, m, x, y+1); }
return sum;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner scn = new Scanner(System.in);
int T = scn.nextInt();
while( T-- > 0 ){
int n = scn.nextInt();
int m = scn.nextInt();
char[][] map = new char[n][m];
boolean[][] check = new boolean[n][m];
for( int i = 0; i<n; i++ ){
String num = scn.next();
map[i] = num.toCharArray();
}
LinkedList<Integer> sums = new LinkedList<>();
for( int i = 0; i < n; i++ ){
for( int j = 0; j < m; j++ ){
if( !check[i][j] && map[i][j] == '1'){
int nsum = matching(map, check, n, m, i, j);
if( nsum != 0 ){ sums.add(nsum); }
}
}
}
Collections.sort( sums, Collections.reverseOrder() );
int res = 0;
for( int i = 1; i < sums.size(); i = i+2 ){
res += sums.get(i);
}
System.out.println(res);
System.err.println();
}
}
}
STDIN
3
4 4
1001
0110
0110
1001
2 2
11
11
3 3
100
010
001
STDOUT
2
0
1
STDERR
0 0
1 0
0 1
0 3
1 3
0 2
1 1
0 1
2 1
1 1
3 1
2 0
2 2
1 2
0 2
2 2
1 1
1 3
3 2
2 1
2 3
1 0
1 2
3 0
2 0
3 1
3 3
2 3
3 2
0 0
1 0
0 0
1 1
0 1
1 1
0 0
1 0
0 1
0 0
1 0
0 1
1 1
0 1
2 1
1 0
1 2
2 2
1 2
2 1
What do you infer from this?
You are visiting the same node again and again. For strong test cases, the recursion depth is so huge causing RTE. You need to visit a cell only if the following conditions hold true.
- You have not visited the cell
- The cell you are gonna visit is ‘1’.
Make these changes and try again.