Sorting a binary 2D matrix?

前端 未结 6 1256
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 13:06

I\'m looking for some pointers here as I don\'t quite know where to start researching this one.

I have a 2D matrix with 0 or 1 in each cell, such as:

  1         


        
6条回答
  •  一向
    一向 (楼主)
    2021-02-09 13:48

    I came up with the below algorithm, and it seems to work correctly.

    Phase 1: move rows with most 1s up and columns with most 1s right.

    1. First the rows. Sort the rows by counting their 1s. We don't care if 2 rows have the same number of 1s.
    2. Now the columns. Sort the cols by counting their 1s. We don't care if 2 cols have the same number of 1s.

    Phase 2: repeat phase 1 but with extra criterions, so that we satisfy the triangular matrix morph.
    Criterion for rows: if 2 rows have the same number of 1s, we move up the row that begin with fewer 0s.

    Criterion for cols: if 2 cols have the same number of 1s, we move right the col that has fewer 0s at the bottom.


    Example:

    Phase 1

      1 2 3 4                     1 2 3 4                   4 1 3 2
    A 0 1 1 0                   B 1 1 1 0                 B 0 1 1 1
    B 1 1 1 0  - sort rows->    A 0 1 1 0  - sort cols->  A 0 0 1 1
    C 0 1 0 0                   D 1 1 0 0                 D 0 1 0 1
    D 1 1 0 0                   C 0 1 0 0                 C 0 0 0 1
    

    Phase 2

      4 1 3 2                     4 1 3 2
    B 0 1 1 1                   B 0 1 1 1
    A 0 0 1 1  - sort rows->    D 0 1 0 1  - sort cols-> "completed"
    D 0 1 0 1                   A 0 0 1 1
    C 0 0 0 1                   C 0 0 0 1
    

    Edit: it turns out that my algorithm doesn't give proper triangular matrices always.
    For example:

    Phase 1

       1 2 3 4                    1 2 3 4                
    A  1 0 0 0                  B 0 1 1 1                
    B  0 1 1 1 - sort rows->    C 0 0 1 1  - sort cols-> "completed"
    C  0 0 1 1                  A 1 0 0 0                
    D  0 0 0 1                  D 0 0 0 1                
    

    Phase 2

       1 2 3 4                    1 2 3 4                   2 1 3 4
    B  0 1 1 1                  B 0 1 1 1                 B 1 0 1 1
    C  0 0 1 1 - sort rows->    C 0 0 1 1  - sort cols->  C 0 0 1 1
    A  1 0 0 0                  A 1 0 0 0                 A 0 1 0 0
    D  0 0 0 1                  D 0 0 0 1                 D 0 0 0 1
                               (no change)
    

    (*) Perhaps a phase 3 will increase the good results. In that phase we place the rows that start with fewer 0s in the top.

提交回复
热议问题