如何在矩阵中的变量周围添加变量
问题描述:
我需要约为2,2的变量之和,然后将其打印出来。如何在矩阵中的变量周围添加变量
我不知道如何做到这一点。请帮忙! 这是我到目前为止的代码:
import java.util.*;
import java.io.*;
public class MatrixSumming
{
private int[][] m = {{5,6},{7,8},{3,4}}; //load in the matrix values
public int sum(int r, int c)
{
return 0;
}
public String toString()
{
return "";
}
}
这里是我的亚军
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class MatrixSummingRunner
{
public static void main(String args[]) throws IOException
{
//Scanner file = new Scanner (new File("matsum.dat"));
int[][] mat = {{0, 0, 0, 0, 0, 0, 0},
{0, 1, 2, 3, 4, 5, 0},
{0, 6, 7, 8, 9, 0, 0},
{0, 6, 7, 1, 2, 5, 0},
{0, 6, 7, 8, 9, 0, 0},
{0, 5, 4, 3, 2, 1, 0},
{0, 0, 0, 0, 0, 0, 0}};
}
}
我试图寻找,但找不到在矩阵类似这样的东西。
答
做所需数量与普通的搜索,让指数vvalues是“CURI”和“curj”
使用下面的逻辑 让马克西和MAXJ为(MXN)矩阵
的m和nsum = 0;
for(int i=curi-1;i<curi+3;i++){
for(int j=curj-1;j<curj+3;j++){
if(i>-1 && j>-1 && i<maxi && j<maxj){ // boundary conditions
if(i!=curi && j!=curj){
continue; // skip the current search key to add
}
sum += array[i][j];
}
}
}
答
该方法将获取所有周围的单元格值并对它们进行求和。
private static int neighboursSum(int[][] grid, int r, int c) {
int sum = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
// Make sure that we don't sum the Original Value, we only want it's neighbours
if (i == 0 && j == 0) {
continue;
} else {
int newX = r + i;
int newY = c + j;
// Make sure that the new Coordinates do not point outside the range of the Array
if (newX >= 0 && newX <= grid.length && newY >= 0 && newY <= grid.length) {
sum += grid[newX][newY];
}
}
}
}
return sum;
}
答
你有这种方法public int sum(int r, int c)
你通过两个整数。
这些是行和列索引,并对应于矩阵中的位置。 (或者你必须减1,如果你把第一行作为第一行,因为Java中的零索引数组)
所以,如果你有一个矩阵和值r和c,你将在位置matrix[r][c]
(或其他方式)。
想象一下,站在棋盘上。现在你有8个领域,你可以通过一步到达。 (或者两个,如果你不能一步一步地移动)。你可能没有一个或多个方面的领域。在计算总和之前,你必须检查它。
现在,采取步骤意味着将r
或c
加1或减1。因此,通过寻址matrix[r-1][c]
或matrix[r][c+1]
等,您可以获得其他指标。要移动对角线,您必须更改r
和c
(分两步,例如先向左移动一个,然后向上移动一个。移动到原始字段左上角的对角字段)
然后,您可以使用此知识访问当前字段周围的字段并将其总和。
你能否提供更清晰的想要达到的目标? – mbsingh
就像我想要它得到像2,2矩阵解释然后在所有8个方向添加2,2所有变量然后打印它 – Will309
如果在一个方向上没有价值会怎么样? (位置0,0) – blueygh2