2015-04-23 109 views
-2

我需要約爲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}}; 
} 
} 

我試圖尋找,但找不到在矩陣類似這樣的東西。

+0

你能否提供更清晰的想要達到的目標? – mbsingh

+0

就像我想要它得到像2,2矩陣解釋然後在所有8個方向添加2,2所有變量然後打印它 – Will309

+0

如果在一個方向上沒有價值會怎麼樣? (位置0,0) – blueygh2

回答

0

做所需數量與普通的搜索,讓指數vvalues是「CURI」和「curj」

使用下面的邏輯 讓馬克西和MAXJ爲(MXN)矩陣

的m和n
sum = 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]; 
     } 
    } 
} 
+0

我會在哪裏準確地放置它? – Will309

+0

我只是給了你一個想法如何做,只是想想。提示:在這裏你正在尋找2,2個位置,因此curi = 2和curj = 2 – HJK

0

該方法將獲取所有周圍的單元格值並對它們進行求和。

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; 
    } 
0

你有這種方法public int sum(int r, int c)你通過兩個整數。

這些是行和列索引,並對應於矩陣中的位置。 (或者你必須減1,如果你把第一行作爲第一行,因爲Java中的零索引數組)

所以,如果你有一個矩陣和值r和c,你將在位置matrix[r][c](或其他方式)。

想象一下,站在棋盤上。現在你有8個領域,你可以通過一步到達。 (或者兩個,如果你不能一步一步地移動)。你可能沒有一個或多個方面的領域。在計算總和之前,你必須檢查它。

現在,採取步驟意味着將rc加1或減1。因此,通過尋址matrix[r-1][c]matrix[r][c+1]等,您可以獲得其他指標。要移動對角線,您必須更改rc(分兩步,例如先向左移動一個,然後向上移動一個。移動到原始字段左上角的對角字段)

然後,您可以使用此知識訪問當前字段周圍的字段並將其總和。