Hello.

Such a question is that the problem in a two-dimensional array when detecting 0 is to move the entire column down (remove zero, move the contents of the top cells to the bottom, fill the hole that appears above from top with zero).

for(int i=9;i>0;i--){ for(int j=9;j>0;j--){ if(field[i][j]==0){ // Тут еще один цикл сделать, или как лучше? } } } 

    2 answers 2

    You can shift right in this loop:

     for(int i=9;i>0;i--){ int shift = 0; for(int j=9;j>0;j--){ while(j-shift>=0 && field[i][j-shift]==0) {// обрабатываем последовательные нули shift++; } if (shift > 0) { // берём значение выше, если есть, иначе заполняем нулями. field[i][j] = j-shift>=0 ? field[i][j-shift] : 0; } } } 

      If there is an array a dimension M x N , then it can be done in cycles as follows

       for ( int j = 0; j != N; j++ ) // цикл по столбцам { int k = M; for ( int i = M; i != 0; i-- ) // цикл по строкам для выбранного столбца { if ( a[i-1][j] != 0 ) { if ( k != i ) a[k-1][j] = a[i-1][j]; --k; } } while ( k != 0 ) a[--k][j] = 0; } 

      Below is a demonstration program.

       import java.util.*; import java.lang.*; import java.io.*; class Ideone { public static void main (String[] args) throws java.lang.Exception { int a[][] = { { 1, 1 }, { 0, 2 }, { 2, 0 }, { 0, 0 }, { 3, 3 } }; for ( int i = 0; i < a.length; i++ ) { for ( int j = 0; j < a[i].length; j++ ) System.out.printf( "%d ", a[i][j] ); System.out.println();; } System.out.println();; for ( int j = 0; j != a[0].length; j++ ) { int k = a.length; for ( int i = a.length; i != 0; i-- ) { if ( a[i-1][j] != 0 ) { if ( k != i ) a[k-1][j] = a[i-1][j]; --k; } } while ( k != 0 ) a[--k][j] = 0; } for ( int i = 0; i < a.length; i++ ) { for ( int j = 0; j < a[i].length; j++ ) System.out.printf( "%d ", a[i][j] ); System.out.println();; } System.out.println();; } } 

      Its output to the console

       1 1 0 2 2 0 0 0 3 3 0 0 0 0 1 1 2 2 3 3 
      • The @MDobroch MOT that you showed simply does not make sense. Initially, the variable c is initialized to 0, and then the while loop contains the while condition (c! = 0). Well, so this cycle will never be executed. - Vlad from Moscow
      • Really ... stupid. Thank! - mDobroch