开发者

Java - traverse a 2D matrix diagnoally, above and to the left

开发者 https://www.devze.com 2023-01-21 15:10 出处:网络
I have a matrix 0 0 0 0 0 0 1 1 2 1 0 1 1 2 2 0 1 1 2 3 So now I would like to understand how to do the following

I have a matrix

0 0 0 0 0
0 1 1 2 1
0 1 1 2 2
0 1 1 2 3

So now I would like to understand how to do the following

First go to the bottom right pick up the first no {which is 3} then traverse diagonally, and then pick the {2} but since the no directly above the diagonal 2 is also 2. I would like to create two pointers one to keep a track of the diagonal and the other for the above.

I have got the dia开发者_StackOverflowgonal code to run, but the code for the directly above one does not work. Can you help me with some ideas?


The problem you may or may not be running into is that the top left element does not have an element above it (array index out of bounds exception). The following code will transverse a square matrix and extract out the values for the above-diagonal values assuming the matrix is strored as a 2D array of doubles with the first index representing row and the second representing column:

double[] values = new double[matrix.length-1];
for (int i = matrix.length - 1; i > 0; i --) {
  value[i-1] = matrix[i-1][i];
}

This will save the values such that the item at value[0] is in row 0 column 1. If you want the reverse the array so that the item at value[0] was the one at the second-to-last row and last colum (directly above the bottom right element, the following code should work:

double[] values = new double[matrix.length-1];
for (int i = matrix.length - 1; i > 0; i --) {
  value[matrix.length - i - 1] = matrix[i-1][i];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号