NZEC in java but not in C++

The code in java got NZEC but the same code with same logic in C++ got Accepted . Can you tell me why ?

Link to the problem http://www.spoj.com/problems/BYTESM2/

C++ code

#include<stdio.h>
#include
#include
#include<stdlib.h>

int max(int a,int b,int c){

int m=a;
if(m<b)
	m=b;
if(m<c)
	m=c;
return m;

}

int main(){

int t;
scanf("%d",&t);
while(t-->0){
	int r,c;
	scanf("%d%d",&r,&c);
	int j=1;
	int arr[r+1][c+2];
	int y=0;
	while(y<=c+1){
		arr[0][y]=0;	
		y+=1;
	}
	y=0;
	while(y<=r){
		arr[y][0]=0;
		y+=1;
	}
	y=0;
	while(y<=r){
		arr[y][c+1]=0;
		y+=1;
	}

	while(j<=r){
		int k=1;
		while(k<=c){
			scanf("%d",&arr[j][k]);	
			k+=1;
		}
		j+=1;
	}

	for(int i=2;i<=r;i++){
		for(j=1;j<=c;j++){
			arr[i][j]+=max(arr[i-1][j],arr[i-1][j-1],arr[i-1][j+1]);

		}	
	}
	int m=0;
	for(j=1;j<=c;j++){
		if(m<arr[r][j])
			m=arr[r][j];
	}
	printf("%d\n",m);
}

}

Here is my Java Code

import java.io.*;

class philosophersstone{

public static void main(String[] args) throws IOException{
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int t=Integer.parseInt(br.readLine());
	for(int i1=0;i1<t;i1++){
		String s=br.readLine();
		String str[]=s.split(" ");
		int r=Integer.parseInt(str[0]);
		int c=Integer.parseInt(str[1]);
		int j=1;
		int arr[][]=new int[r+1][c+2];
		while(j<=r){
			s=br.readLine();
			str=s.split(" ");
			int k=1;
			while(k<=c){
				arr[j][k]=Integer.parseInt(str[k-1]);	
				k+=1;
			}
			j+=1;	
		}


		for(int i=2;i<=r;i++){
			for( j=1;j<=c;j++){
				arr[i][j]+=max(arr[i-1][j],arr[i-1][j-1],arr[i-1][j+1]);
			}	
		}
		int m=0;
		for(j=1;j<=c;j++){
			if(m<arr[r][j])
				m=arr[r][j];
		}
		System.out.println(m);
	}
}

public static int max(int a,int b,int c){
	int max=a;
	if(max<b){
		max=b;	
	}
	if(max<c){
		max=c;	
	}
	return max;
}

}

1 Like

One reason can be index overflow in array, Java is strict in this, C/C++ doesn’t care much… Try to use bigger array, let say instead of int[100000] use for example int[100010]

1 Like

Please provide link to the question and to both of the code that are mentioned in the question. Only then we’ll be able to help you.

//