This is a simple task that sum elements in matrix in 'zigzag' move by horizontal. The variable 'sumPath' need to be long and it throw me 'java.lang.OutOfMemoryError'.
I have two 'for' cycles and need to shorten them.
How I could do it ?
Here is the code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.next());
int m = Integer.parseInt(scanner.next());
int[][] matrix = new int[n][m];
long sumPath = 1;
matrix[0][0] = 1;
for (int row = 0; row < n; row++) {
if (row > 0) {
matrix[row][0] = matrix[row - 1][0] + 3;
}
for (int col = 1; col < m; col++) {
matrix[row][col] = matrix[row][col - 1] + 3;
}
}
int row = 0;
while (row < n-1) {
for (int col = 1; col < m; col++) {
if (col % 2 == 0) {
sumPath = sumPath + matrix[row][col];
} else {
sumPath = sumPath + matrix[row+1][col];
}
}
row = row + 2;
if (row >= n) {
break;
}
for (int col = m - 2; col >= 0; col--) {
if (col % 2 == 0) {
sumPath = sumPath + matrix[row][col];
} else {
sumPath = sumPath + matrix[row-1][col];
}
}
}
System.out.println(sumPath);
}
}