Home » Java » java – Solution to algorithm problem has slightly incorrect output. What's wrong?-Exceptionshub

# java – Solution to algorithm problem has slightly incorrect output. What's wrong?-Exceptionshub

Questions:

The problem was taken from here

Description:
You are given a two-dimensional array (matrix) of potentially unequal height and width containing only 0s and 1s. Each 0 represents land, and each 1 represents part of a river. A river consists of any number of 1s that are either horizontally or vertically adjacent (but not diagonally adjacent). The number of adjacent 1s forming a river determine its size. Write a function that returns an array of the sizes of all rivers represented in the input matrix. Note that these sizes do not need to be in any particular order.

``````Sample input:
[
[1, 0, 0, 1, 0],
[1, 0, 1, 0, 0],
[0, 0, 1, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 1, 1, 0],
]
Sample output:
[1, 2, 2, 2, 5]
``````

My solution:

I tried to solve this problem using Depth-First-Search recursively.

``````import java.util.*;
class River{
int size;
int[][]matrix;
River(int[][]mat){
matrix=mat;
}
void traverse(int x,int y){
System.out.println(x+","+y);
if((y-1)>=matrix.length && matrix[x][y-1]==1){
size++;
matrix[x][y-1]=0;
traverse(x,y-1);
} if((x+1)<matrix.length && matrix[x+1][y]==1){
size++;
matrix[x+1][y]=0;
traverse(x+1,y);
}if((x-1)>=matrix.length && matrix[x-1][y]==1){
size++;
matrix[x-1][y]=0;
traverse(x-1,y);
}
if((y+1)<matrix.length && matrix[x][y+1]==1){
size++;
matrix[x][y+1]=0;
traverse(x,y+1);
}
}
}
class Program {
public static List<Integer> riverSizes(int[][] matrix) {
List<Integer> SList = new ArrayList<>();
List<River> RList = new ArrayList<>();
System.out.println("Traversal:");

for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix.length;j++){
if(matrix[i][j]==1){
matrix[i][j]=0;
River river = new River(matrix);
river.size++;
river.traverse(i,j);
}
}
}
System.out.println("Sizes:");
for(River r:RList){
System.out.println(r.size);
}
return SList;
}
public static void main(String[]args){
int[][]riverM={
{1,0,0,0,0,0,1},
{0,1,0,0,0,1,0},
{0,0,1,0,1,0,0},
{0,0,1,1,1,0,0},
{0,0,1,0,1,0,0},
{0,1,0,0,0,1,0},
{1,0,0,0,0,0,1},
};

System.out.println("("+riverM.length+","+riverM.length+")");
riverSizes(riverM);
}
}
``````

My output passed 7/12 cases. This is one of the case that went wrong.

My Output:

``````Sizes:
1,1,1,1,6,1,1,1,1,1,
``````

Expected Output:

``````Sizes:
1,1,1,1,7,1,1,1,1,1,
``````

Can someone tell me what’s going wrong?

I think the problem is located into your `traverse` function:
``````if((y-1)>=matrix.length && matrix[x][y-1]==1){...}
The left part of the condition `(y-1)>=matrix.length` is wrong. Here, correct me if I’m wrong, you just want to prevent `IndexOutOfBoundsException`. To do it, you should test something like `(y-1) >= 0`.
Same error when you’re testing your `x` index. Test the output with these fixes, didn’t check if there’s something else wrong.