2017-12-03 264 views
-2

我想給出一個矩陣,任何數字,如果它發現零,降低那些非空的元素。 例如,對於矩陣向下移動矩陣的元素java

1 2 3 4 5 
6 7 8 0 0 
0 12 0 14 0 
0 0 18 19 0 
0 22 23 24 25 

輸出將是

0 0 0 0 0 
0 2 3 4 0 
0 7 8 14 0 
1 12 18 19 5 
6 22 23 24 25 

剩餘上面的零,移動元件向下順序。我有這樣的代碼:

public static void displace(int[][] matrix, int size) { 
    int cont=1; 
    for (int col = 0; col < size; col++) { 
     cont = 1; 
     for (int row = 0; row < size; row++) { 
      if (matrix[row][col] == 0) { 
       matrix[row-1][col]=matrix[row][col]; 
       cont++; 
      } 
     } 
    } 
} 

,這讓我是一個零,以取代該行的第一個數字,那就是,它採用零和位置上升的唯一的事情。

+0

而你的問題是... –

+0

這是我的代碼不工作,我不把它做好,我不知道錯誤。如果你讀了所有的東西,你可以看到我已經寫下了「唯一讓我做的就是用零替換行的第一個數字,也就是說,它需要零和一個位置上升。」 – Fernando

+2

我已經低估了這個問題,因爲沒有任何對此代碼執行任何調試的證據。請[編輯]您的問題,向我們展示您的調試未發現的內容,以及關於特定代碼行的具體問題。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)和[如何調試小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs /) –

回答

1

對於未來的問題,考慮發佈mcve像喬C評論。 消除任何不相關(如int[] colorint position像STaefi評論),並以易於提供的測試數據使用的形式,像這樣:

public static void main(String[] args) { 

    int[][] matrix1 = {{1,2, 3 ,4 ,5}, 
         {6,7, 8, 0, 0}, 
         {0,12, 0,14, 0}, 
         {0,0, 18,19, 0}, 
         {0,22,23,24, 25} 
    } ; 

    displace(matrix1); 
    for(int[] row : matrix1) { 

     System.out.println(Arrays.toString(row)); 
    } 
} 

至於解決:你需要重複這個過程,直到所有掉期都完成了。

public static void displace(int[][] matrix) { 

    int swapCount= 1; 

    while (swapCount > 0) { 

     swapCount = 0; 
     for (int col = 0; col < matrix[0].length; col++) { 
      for (int row = 0; row < matrix.length; row++) { 
       if (matrix[row][col] == 0) { 
        if(((row-1) >= 0) && (matrix[row-1][col] != 0)) { 
         //do swap 
         matrix[row][col] = matrix[row-1][col]; 
         matrix[row-1][col]= 0; 
         swapCount++; 
        } 
       } 
      } 
     } 
    } 
}