2015-07-05 40 views
0

我想將char[][]數組(我們稱之爲cA)變成一個鄰接矩陣。鄰接矩陣的列和行等於數組中元素的數量,並且鄰接矩陣中的每個頂點是truefalse,具體取決於初始數組中的元素是否相鄰。我想稍微彎曲這些規則,並且還會將鄰接矩陣頂點約束爲true,如果元素相鄰,則其中一個元素不是特定值。從char [] []提供規則創建鄰接矩陣

這裏是cA陣列的樣子:

z y z 
z z z 
z y y 

鄰接矩陣(可以稱之爲aM)爲cA陣列將是一個int數組的大小[3*3][3*3]的。將aM(i,j)設置爲true的條件是ij中的cA數組必須相鄰,但ij都不能爲「y」。

允許數量cA陣列元素1至9

1 2 3 
4 5 6 
7 8 9 

aM可以通過執行以下操作來描述:

aM(1,1) //false, no self-adjacency 
aM(1,2) //false, 2 is a "y" 
aM(1,3) //false, 1 is not adjacent to 3 
aM(1,4) //true, 1 is adjacent to 4, neither are "y" 
aM(1,5) //false, 1 is not adjacent to 5 
aM(1,6) //false, 1 is not adjacent to 6 
aM(1,7) through aM(1,9) //false, there is no adjacency between 1 and 7, 8, or 9 
aM(2,1) through aM(2,9) //false, 2 is a "y" 
... 

希望你的想法。根據以上所述,對於cA鄰接矩陣是如下:

1 2 3 4 5 6 7 8 9 (i) 
1 0 0 0 1 0 0 0 0 0 
2 0 0 0 0 0 0 0 0 0 
3 0 0 0 0 0 1 0 0 0 
4 1 0 0 0 1 0 1 0 0 
5 0 0 0 1 0 1 0 0 0 
6 0 0 1 0 1 0 0 0 0 
7 0 0 0 1 0 0 0 0 0 
8 0 0 0 0 0 0 0 0 0 
9 0 0 0 0 0 0 0 0 0 
(j) 

該規則是當且僅當aM(i,j) == 1i != ji != "y" && j != "y",並且兩個ij是彼此相鄰的。

我很難調配一個算法來創建一個鄰接矩陣,提供了一個char[][]數組。我已經定義了規則,但是爲迭代找到約束是有問題的。

回答

1

試試這個:

static void set(boolean[][] aM, int cols, int row0, int col0, int row1, int col1) { 
    int index0 = row0 * cols + col0; 
    int index1 = row1 * cols + col1; 
    aM[index0][index1] = aM[index1][index0] = true; 
} 

static boolean[][] adjacencyMatrix(char[][] cA) { 
    int rows = cA.length; 
    int cols = cA[0].length; 
    boolean[][] aM = new boolean[rows * cols][rows * cols]; 
    for (int i = 0; i < rows; ++i) { 
     for (int j = 0; j < cols; ++j) { 
      if (cA[i][j] == 'y') 
       continue; 
      if (i + 1 < rows && cA[i + 1][j] != 'y') 
       set(aM, cols, i, j, i + 1, j); 
      if (j + 1 < cols && cA[i][j + 1] != 'y') 
       set(aM, cols, i, j, i, j + 1); 
     } 
    } 
    return aM; 
} 

public static void main(String[] args) { 
    char[][] cA = { 
     {'z', 'y', 'z'}, 
     {'z', 'z', 'z'}, 
     {'z', 'y', 'y'}, 
    }; 
    boolean[][] aM = adjacencyMatrix(cA); 
    for (boolean[] row : aM) { 
     for (boolean cell : row) 
      System.out.print(cell ? "1" : "0"); 
     System.out.println(); 
    } 
} 

結果是:

000100000 
000000000 
000001000 
100010100 
000101000 
001010000 
000100000 
000000000 
000000000 
+0

太好了,這工作出色。我注意到所有的鄰接矩陣都是沿對角線對稱的,對角線總是'{0}'(除非自相鄰可能,那麼它是'{1}')。僅僅爲上三角矩陣計算aM(i,j),然後再複製到下三角矩陣會更有效率嗎? 'aM(i,j)'總是等於'aM(j,i)'。 – gator

+0

請參閱我的代碼的第4行('aM [index0] [index1] = aM [index1] [index0] = true;')。該算法僅計算單向鄰接。結果存儲在兩個地方'aM(i,j)'和'aM(j,i)'。如果將結果矩陣更改爲三角形,則可以節省內存,但不能節省時間。 – saka1029