Shift all zeros in 2d matrix

I have a 2d array like this:

2 0 0 2 0 4
2 0 0 2 0 4
2 0 0 2 0 4

And I want to move all zeros to the left, so for this I did this method:

public static void shiftLeft(int [][] array){

    for (int j = 0; j < array.length; j++) {

        for (int i = 0; i < array.length - 1; i++) {

            if ((array[j][i] != 0) && (array[j][i + 1] == 0)) {
                array[j][i + 1] = array[j][i];
                array[j][i] = 0;
            }
        }
    }
}

But the conclusion I get is this:

0 0 2 0 2 4
0 0 2 0 2 4
0 0 2 0 2 4

How can I make all zeros go left?

+4
source share
2 answers

In my opinion, the easiest way to do this is to use 3 nested loops.

The variable i is repeated line by line.

The variable j1 finds the first nonzero element starting to the left of each row.

j2 j1 . , A ​​ A [N] [M], N M - .

for(int i =0;i<N;i++){
  for(int j1=0;j1<M;j1++){
    if (A[i][j1]==0)
      continue;
    for(int j2=j1;j2<M;j2++){
      if( A[i][j2]==0){
         //swap
         int tmp=A[i][j1];
         A[i][j1]=A[i][j2];
         A[i][j2]=tmp;
       }
     }
  }
}
+2

Trugis , . , .

:

    int[][] A = {   { 2, 3, 4, 2, 4, 4, 5, 0, 0, 0 },
                    { 0, 0, 0, 0, 0, 4, 3, 4, 5, 6 },
                    { 2, 0, 4, 2, 0, 4, 1, 2, 3, 4 }};

    int N = A.length;
    int M = A[0].length;
    int firstZeros = 0;

    for(int i = 0; i < N; i++) { // Loop over the rows 
        for(int j1 = 0; j1 < M; j1++) {
            // If there is a zero we pass by
            if (A[i][j1] == 0 && firstZeros == j1) {
                firstZeros++;
                continue;
            }
            // Otherwise, we have a value so we want to check if there is a zero afterwards
            for(int j2 = j1+1; j2 < M; j2++) {
                // If we find a zero we move it to the left
                if(A[i][j2] == 0) {
                    for (int j3 = j2; j3 > firstZeros; j3--) {
                        // Change zero with previous value
                        A[i][j3] = A[i][j3-1];
                        A[i][j3-1] = 0;
                    }
                    firstZeros++;
                }
            }
        }
        firstZeros = 0;
    }
0

Source: https://habr.com/ru/post/1688678/


All Articles