2017-08-28 61 views
1

嗨即時嘗試獲取所有鄰居或相鄰的值是相等的,在一個二維數組中我已經搜索了很多,但答案不適合我 示例:2d數組的相鄰值(java)

`|1|0|1|` 
`|0|1|1|` 
`|0|1|0|` 

總相鄰:4

int rowLimit = grid.length; 
    int columnLimit = grid.length; 

    for (int i = 0; i < grid.length; i++) { 
     for (int j = 0; j < grid[i].length; j++) { 
      for(int x = Math.max(0, i-1); x <= Math.min(i+1, rowLimit); x++) { 
       for(int y = Math.max(0, j-1); y <= Math.min(j+1, columnLimit); y++) { 
        if(x != i || y != j) { 
         adj++; 
        } 
       } 
      }  
     } 
    } 



    System.out.println("Total adjacent:" + ady); 
+0

在紙上手動瀏覽您的示例,然後轉換爲代碼。如果代碼仍然無法使用調試器。 –

回答

0

這是另一種算法(在我看來,比您的算法更簡單):

int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}}; 
int counter = 0; 

int rowLimit = array.length; 
int colLimit = array[0].length; 

for (int r = 0; r < rowLimit; r++) 
{ 
    for (int c = 0; c < colLimit; c++) 
    { 
    if ((c+1 < colLimit) && (array[r][c] == array[r][c+1])) 
     counter++; 

    if ((r+1 < rowLimit) && (array[r][c] == array[r+1][c])) 
     counter++; 
    } 
} 
0

這裏是一個可行的解決方案:

int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}}; 

    int rowLimit = array.length; 
    int columnLimit = array[0].length; 

    int actualValue; 
    int sum = 0; 

    for(int i = 0; i < rowLimit; i++) { 
     for(int j = 0; j < columnLimit; j++) { 
      actualValue = array[i][j]; 
       for(int x = Math.max(0, i-1); x <= Math.min(i+1, rowLimit-1); x++){ 
        for(int y = Math.max(0, j-1); y <= Math.min(j+1, columnLimit-1); y++){ 
         if(x != i || y != j){ 
          if(actualValue == array[x][y] && (Math.abs(x-i) + abs(y-j) == 1)) 
           sum++; 
         } 
        } 

      } 
     } 
    } 

    System.out.println("Total adjacent: " + sum/2);