2017-12-03 263 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++; 
        } 
       } 
      } 
     } 
    } 
}