Isabel Alphonse - 6 months ago 32

Java Question

So I have a 2D matrix and I'm trying to print out the values from largest to smallest. I basically do this by always looking for a max and when I find it I set that position equal to

`1`

`adjacencyMatrix`

Here is my code:

`public static void findLongestPath(int rows, int columns, int[][] elevationMatrix, int[][] adjacencyMatrix)`

{

int max = 0;

for (int x = 0; x < rows * columns; x++)

{

for (int i = 0; i < rows; i++)

{

for (int j = 0; j < columns; j++)

{

if (elevationMatrix[i][j] > max && adjacencyMatrix[i][j] == 0)

{

max = elevationMatrix[i][j];

adjacencyMatrix[i][j] = 1;

}

}

}

System.out.println(max);

max = 0;

}

}

I have been staring at it for a while and can't find the bug so I though another pair of eyes might help.

P.S. Please, please, please don't tell me to sort the array because I can'd do that. I need to maintain the order of the original array.

Answer

```
public static void findLongestPath(int rows, int columns, int[][] elevationMatrix, int[][] adjacencyMatrix)
{
int max = 0;
int cX, cY;
for (int x = 0; x < rows * columns; x++)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if (elevationMatrix[i][j] > max && adjacencyMatrix[i][j] == 0)
{
max = elevationMatrix[i][j]; // possible max
cX = i; // store i
cY = j; // store j
}
}
}
System.out.println(max); // global max
max = 0;
// cX and cJ now point to coordinates of global max
// all the possible max value coordinates are ignored.
adjacencyMatrix[cX][cJ] = 1;
}
}
```

I think you need to set `adjacencyMatrix[][] = 1`

, after you find largest number throughout the matrix(global max), rather than finding a max(possible max).

There can be more efficient ways to do this, I'm pointing out at what needs to be done in this method to work.