Algorithme hongrois: trouver le nombre minimum de lignes pour couvrir des zéros?

j'essaie de mettre en œuvre l'algorithme hongrois 151970920" mais je suis coincé sur le étape 5 . Fondamentalement, étant donné une matrice de nombres n X n , Comment puis-je trouver le nombre minimum de lignes verticales+horizontales telles que les zéros dans la matrice sont couverts?

avant que quelqu'un marque cette question comme un duplicata de ce , la solution mentionnée là est incorrecte et quelqu'un d'autre a également rencontré le bug dans le code posté là .

Je ne cherche pas le code mais plutôt le concept par lequel je peux tracer ces lignes...

EDIT: Merci de ne pas poster la simple (mais mal) algorithme glouton: Compte tenu de cette entrée:

(0, 1, 0, 1, 1)
(1, 1, 0, 1, 1)
(1, 0, 0, 0, 1)
(1, 1, 0, 1, 1)
(1, 0, 0, 1, 0)

je sélectionne, colonne 2 évidemment (0-indexé):

(0, 1, x, 1, 1)
(1, 1, x, 1, 1)
(1, 0, x, 0, 1)
(1, 1, x, 1, 1)
(1, 0, x, 1, 0)

maintenant je peux choisir la ligne 2 ou la col 1 qui ont toutes les deux deux "autres" zéros. Si je sélectionne col2, je me retrouve avec la mauvaise solution dans cette voie:

(0, x, x, 1, 1)
(1, x, x, 1, 1)
(1, x, x, 0, 1)
(1, x, x, 1, 1)
(1, x, x, 1, 0)

la bonne solution est d'utiliser 4 lignes:

(x, x, x, x, x)
(1, 1, x, 1, 1)
(x, x, x, x, x)
(1, 1, x, 1, 1)
(x, x, x, x, x)
21
demandé sur Community 2014-04-30 08:23:43

5 réponses

mise à Jour

j'ai mis en œuvre l'algorithme hongrois dans les mêmes étapes fournies par le lien que vous avez posté: algorithme hongrois

Voici les fichiers avec les commentaires: Github

algorithme (Greedy amélioré) pour l'étape 3: (ce code est très détaillé et bon pour comprendre le concept du choix de la ligne à dessiner: horizontale vs verticale. Mais notez que ce code step est amélioré dans mon code dans Github )

  • calculer le nombre maximal de zéros verticalement vs horizontalement pour chaque position xy dans la matrice d'entrée et stocker le résultat dans un tableau séparé appelé m2 .
  • en calculant, si les zéros horizontaux > les zéros verticaux, alors le nombre calculé est converti au négatif. (juste pour distinguer quelle direction nous avons choisi pour une utilisation ultérieure)
  • boucle à travers tous les éléments du tableau m2 . Si la valeur est positive, tracez une ligne verticale dans la gamme m3 , si la valeur est négative, tracez une ligne horizontale dans m3

suivre l'exemple ci-dessous + code pour mieux comprendre l'algorithme:

Créer 3 tableaux:

  • m1: Premier tableau, détient les valeurs d'entrée
  • m2: deuxième rangée, tient des maxZeroes (verticaux, horizontaux) à chaque position x, y
  • m3: Troisième tableau, tient les lignes finales (0 indice non couvert, 1 Indice couvert)

créer 2 fonctions:

  • hvMax( m1, row, col); renvoie le nombre maximum de zéros horizontal ou vertical. (Un nombre positif signifie vertical, un nombre négatif signifie horizontal)
  • clearNeighbours (m2, m3,rangée,col); méthode des vides, elle nettoie les voisins horizontaux si la valeur des indices de la rangée col est négative, ou les voisins verticaux clairs si positifs. De plus, il positionnera la ligne dans le tableau m3, en retournant le zéro bit à 1.

Code

public class Hungarian {
    public static void main(String[] args) {
        // m1 input values
        int[][] m1 = { { 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 0, 0, 1 },
                { 1, 1, 0, 1, 1 }, { 1, 0, 0, 1, 0 } };

        // int[][] m1 = { {13,14,0,8},
        // {40,0,12,40},
        // {6,64,0,66},
        // {0,1,90,0}};

        // int[][] m1 = { {0,0,100},
        // {50,100,0},
        // {0,50,50}};

        // m2 max(horizontal,vertical) values, with negative number for
        // horizontal, positive for vertical
        int[][] m2 = new int[m1.length][m1.length];

        // m3 where the line are drawen
        int[][] m3 = new int[m1.length][m1.length];

        // loop on zeroes from the input array, and sotre the max num of zeroes
        // in the m2 array
        for (int row = 0; row < m1.length; row++) {
            for (int col = 0; col < m1.length; col++) {
                if (m1[row][col] == 0)
                    m2[row][col] = hvMax(m1, row, col);
            }
        }

        // print m1 array (Given input array)
        System.out.println("Given input array");
        for (int row = 0; row < m1.length; row++) {
            for (int col = 0; col < m1.length; col++) {
                System.out.print(m1[row][col] + "\t");
            }
            System.out.println();
        }

        // print m2 array 
        System.out
                .println("\nm2 array (max num of zeroes from horizontal vs vertical) (- for horizontal and + for vertical)");
        for (int row = 0; row < m1.length; row++) {
            for (int col = 0; col < m1.length; col++) {
                System.out.print(m2[row][col] + "\t");
            }
            System.out.println();
        }

        // Loop on m2 elements, clear neighbours and draw the lines
        for (int row = 0; row < m1.length; row++) {
            for (int col = 0; col < m1.length; col++) {
                if (Math.abs(m2[row][col]) > 0) {
                    clearNeighbours(m2, m3, row, col);
                }
            }
        }

        // prinit m3 array (Lines array)
        System.out.println("\nLines array");
        for (int row = 0; row < m1.length; row++) {
            for (int col = 0; col < m1.length; col++) {
                System.out.print(m3[row][col] + "\t");
            }
            System.out.println();
        }
    }

    // max of vertical vs horizontal at index row col
    public static int hvMax(int[][] m1, int row, int col) {
        int vertical = 0;
        int horizontal = 0;

        // check horizontal
        for (int i = 0; i < m1.length; i++) {
            if (m1[row][i] == 0)
                horizontal++;
        }

        // check vertical
        for (int i = 0; i < m1.length; i++) {
            if (m1[i][col] == 0)
                vertical++;
        }

        // negative for horizontal, positive for vertical
        return vertical > horizontal ? vertical : horizontal * -1;
    }

    // clear the neighbors of the picked largest value, the sign will let the
    // app decide which direction to clear
    public static void clearNeighbours(int[][] m2, int[][] m3, int row, int col) {
        // if vertical
        if (m2[row][col] > 0) {
            for (int i = 0; i < m2.length; i++) {
                if (m2[i][col] > 0)
                    m2[i][col] = 0; // clear neigbor
                m3[i][col] = 1; // draw line
            }
        } else {
            for (int i = 0; i < m2.length; i++) {
                if (m2[row][i] < 0)
                    m2[row][i] = 0; // clear neigbor
                m3[row][i] = 1; // draw line
            }
        }

        m2[row][col] = 0;
        m3[row][col] = 1;
    }
}

Sortie

Given input array
0   1   0   1   1   
1   1   0   1   1   
1   0   0   0   1   
1   1   0   1   1   
1   0   0   1   0   

m2 array (max num of zeroes from horizontal vs vertical) (- for horizontal and + for vertical)
-2  0   5   0   0   
0   0   5   0   0   
0   -3  5   -3  0   
0   0   5   0   0   
0   -3  5   0   -3  

Lines array
1   1   1   1   1   
0   0   1   0   0   
1   1   1   1   1   
0   0   1   0   0   
1   1   1   1   1   

PS: votre exemple que vous avez indiqué, ne se produira jamais parce que comme vous pouvez voir la première boucle faire les calculs en prenant le max(horizontal,vertical) et les sauver en m2. Donc col1 ne sera pas sélectionné parce que -3 signifie tracer la ligne horizontale, et -3 a été calculé en prenant le max entre les zéros horizontaux vs verticaux. Donc, à la première itération sur les éléments, le programme a vérifié comment dessiner les lignes, sur la deuxième itération, le programme dessine les lignes.

11
répondu CMPS 2014-05-04 20:06:46

algorithmes cupides peuvent ne pas fonctionner dans certains cas.

tout d'abord, il est possible de reformuler votre problème comme suit: étant donné un graphe bipartite, trouver un minimum de couverture vertex. Dans ce problème, il existe 2n nœuds de n lignes et n colonnes. Il y a un bord entre deux noeuds si l'élément à l'intersection de la colonne correspondante et de la rangée est zéro. La couverture de sommet est un ensemble de noeuds (lignes et colonnes) tel que chaque bord est incident à un certain noeud de cet ensemble (chaque zéro est couvert par ligne ou colonne).

c'est un problème bien connu qui peut être résolu en O(N^3) en trouvant une correspondance maximale. Vérifier wikipedia pour plus de détails

4
répondu Wanderer 2015-04-29 01:17:40

il y a des cas où le code D'Amir échoue.

Envisager la suite de m1:

 0  0  1

 0  1  1

 1  0  1

La meilleure solution est de tracer des lignes verticales dans les deux premières colonnes.

le code D'Amir donnerait le m2 suivant:

-2 -2  0

 2  0  0

 0  2  0

et le résultat dessinerait les deux lignes verticales ainsi qu'une ligne dans la première rangée.

il me semble que le problème est casse-cravate:

return vertical > horizontal ? vertical : horizontal * -1;

en raison de la façon dont le code est écrit, la m1 très similaire ne manquera pas:

 0  1  1

 1  0  1

 0  0  1

où la première rangée est déplacée vers le bas, parce que la fonction de dégagement va effacer les valeurs de -2 de m2 avant que ces cellules sont atteintes. Dans le premier cas, les valeurs -2 sont frappées en premier, de sorte qu'une ligne horizontale est tracée à travers la première rangée.

j'ai travaillé un peu grâce à cela, et c'est ce que j'ai. Dans le cas d'une égalité, ne fixez aucune valeur et ne tracez pas de ligne à travers ces cellules. Cela couvre le cas de la matrice que j'ai mentionné ci-dessus, nous sommes faits à cette étape.

de toute évidence, il y a des situations où il restera des pièces qui ne seront pas découvertes. Voici un autre exemple de matrice qui échouera dans la méthode d'Amir (m1):

 0 0 1 1 1
 0 1 0 1 1
 0 1 1 0 1
 1 1 0 0 1
 1 1 1 1 1

la solution optimale est de quatre lignes, par exemple les quatre premières. colonne.

la méthode D'Amir donne m2:

 3 -2  0  0  0
 3  0 -2  0  0
 3  0  0 -2  0
 0  0 -2 -2  0
 0  0  0  0  0

qui va tracer des lignes aux quatre premières lignes et la première colonne (une solution incorrecte, donnant 5 lignes). Encore une fois, l'affaire du disjoncteur est la question. Nous résolvons cela en ne fixant pas de valeur pour les liens, et en itérant la procédure.

si nous ignorons les liens nous obtenons un m2:

 3 -2  0  0  0
 3  0  0  0  0
 3  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0

cela conduit à ne couvrir que la première rangée et la la première colonne. Nous sortons alors les 0 qui sont couverts pour donner la nouvelle m1:

 1 1 1 1 1
 1 1 0 1 1
 1 1 1 0 1
 1 1 0 0 1
 1 1 1 1 1

ensuite nous continuons à répéter la procédure (ignorant les liens) jusqu'à ce que nous parvenions à une solution. Répéter pour un nouveau m2:

 0  0  0  0  0
 0  0  2  0  0
 0  0  0  2  0
 0  0  0  0  0
 0  0  0  0  0

, Qui conduit à deux lignes verticales à travers les deuxième et troisième colonnes. Tous les 0s sont maintenant couverts, n'ayant besoin que de quatre lignes (c'est une alternative au revêtement des quatre premières colonnes). La matrice doit seulement 2 itérations, et j'imagine la plupart de ces cas ne nécessiteront que deux itérations, à moins qu'il n'y ait des ensembles de liens imbriqués dans des ensembles de liens. J'ai essayé de venir avec un, mais il est devenu difficile à gérer.

malheureusement, ce n'est pas suffisant, car il y aura des CAs qui resteront liés pour toujours. En particulier, dans les cas où il existe un "ensemble disjoint de cellules liées". Je ne sais pas comment le décrire autrement, sauf pour tirer les deux exemples suivants:

 0 0 1 1
 0 1 1 1
 1 0 1 1
 1 1 1 0

ou

 0 0 1 1 1
 0 1 1 1 1
 1 0 1 1 1
 1 1 1 0 0
 1 1 1 0 0

les sous-matrices 3x3 en haut à gauche dans ces deux exemples sont identiques à mon exemple original, j'ai ajouté 1 ou 2 lignes/colonnes à cet exemple en bas et à droite. Les seuls zéros nouvellement ajoutés sont ceux où les nouvelles lignes et les nouvelles colonnes se croisent. Décrire pour plus de clarté.

avec la méthode itérative que j'ai décrite, ces matrices seront capturées dans une boucle infinie. Les zéros restera toujours attaché (col-comte vs ligne-comte). À ce stade, il l'idée de simplement choisir arbitrairement un sens dans le cas d'une égalité, au moins de ce que je peux imaginer.

le seul problème que je rencontre est de définir les critères d'arrêt de la boucle. Je ne peux pas supposer que 2 itérations est assez (ou n), mais je ne peux pas comprendre comment détecter si une matrice a seulement les boucles infinies gauche. Je ne sais toujours pas comment décrire ces ensembles de calcul liés disjoints.

voici le code pour faire ce que j'ai inventé jusqu'à présent (en écriture MATLAB):

function [Lines, AllRows, AllCols] = FindMinLines(InMat)

%The following code finds the minimum set of lines (rows and columns)
%required to cover all of the true-valued cells in a matrix. If using for
%the Hungarian problem where 'true-values' are equal to zero, make the
%necessary changes. This code is not complete, since it will be caught in 
%an infinite loop in the case of disjoint-tied-sets

%If passing in a matrix where 0s are the cells of interest, uncomment the
%next line
%InMat = InMat == 0;

%Assume square matrix
Count = length(InMat);
Lines = zeros(Count);

%while there are any 'true' values not covered by lines

while any(any(~Lines & InMat))
    %Calculate row-wise and col-wise totals of 'trues' not-already-covered
    HorzCount = repmat(sum(~Lines & InMat, 2), 1, Count).*(~Lines & InMat);
    VertCount = repmat(sum(~Lines & InMat, 1), Count, 1).*(~Lines & InMat);

    %Calculate for each cell the difference between row-wise and col-wise
    %counts. I.e. row-oriented cells will have a negative number, col-oriented
    %cells will have a positive numbers, ties and 'non-trues' will be 0.
    %Non-zero values indicate lines to be drawn where orientation is determined
    %by sign. 
    DiffCounts = VertCount - HorzCount;

    %find the row and col indices of the lines
    HorzIdx = any(DiffCounts < 0, 2);
    VertIdx = any(DiffCounts > 0, 1);

    %Set the horizontal and vertical indices of the Lines matrix to true
    Lines(HorzIdx, :) = true;
    Lines(:, VertIdx) = true;
end

%compute index numbers to be returned. 
AllRows = [find(HorzIdx); find(DisjTiedRows)];
AllCols = find(VertIdx);

end
3
répondu mhermher 2015-01-03 02:02:44

Étape 5: Le dessin de ligne dans la matrice est évalué diagonalement avec un maximum d'évaluations de la longueur de la matrice.

basé sur http://www.wikihow.com/Use-the-Hungarian-Algorithm avec les étapes 1 à 8 seulement.

exécuter l'extrait de code et voir les résultats dans la console

Sortie De La Console

horizontal line (row): {"0":0,"2":2,"4":4}
vertical line (column): {"2":2}

Step 5: Matrix
0  1  0  1  1  
1  1  0  1  1  
1  0  0  0  1  
1  1  0  1  1  
1  0  0  1  0  

Smallest number in uncovered matrix: 1
Step 6: Matrix
x  x  x  x  x  
1  1  x  1  1  
x  x  x  x  x  
1  1  x  1  1  
x  x  x  x  x

JSFiddle: http://jsfiddle.net/jjcosare/6Lpz5gt9/2 /

// http://www.wikihow.com/Use-the-Hungarian-Algorithm

var inputMatrix = [
  [0, 1, 0, 1, 1],
  [1, 1, 0, 1, 1],
  [1, 0, 0, 0, 1],
  [1, 1, 0, 1, 1],
  [1, 0, 0, 1, 0]
];

//var inputMatrix = [
//      [10, 19, 8, 15],
//      [10, 18, 7, 17],
//      [13, 16, 9, 14],
//      [12, 19, 8, 18],
//      [14, 17, 10, 19]
//    ];

var matrix = inputMatrix;
var HungarianAlgorithm = {};

HungarianAlgorithm.step1 = function(stepNumber) {

  console.log("Step " + stepNumber + ": Matrix");

  var currentNumber = 0;
  for (var i = 0; i < matrix.length; i++) {
    var sb = "";
    for (var j = 0; j < matrix[i].length; j++) {
      currentNumber = matrix[i][j];
      sb += currentNumber + "  ";
    }
    console.log(sb);
  }
}

HungarianAlgorithm.step2 = function() {
  var largestNumberInMatrix = getLargestNumberInMatrix(matrix);
  var rowLength = matrix.length;
  var columnLength = matrix[0].length;
  var dummyMatrixToAdd = 0;
  var isAddColumn = rowLength > columnLength;
  var isAddRow = columnLength > rowLength;

  if (isAddColumn) {
    dummyMatrixToAdd = rowLength - columnLength;
    for (var i = 0; i < rowLength; i++) {
      for (var j = columnLength; j < (columnLength + dummyMatrixToAdd); j++) {
        matrix[i][j] = largestNumberInMatrix;
      }
    }
  } else if (isAddRow) {
    dummyMatrixToAdd = columnLength - rowLength;
    for (var i = rowLength; i < (rowLength + dummyMatrixToAdd); i++) {
      matrix[i] = [];
      for (var j = 0; j < columnLength; j++) {
        matrix[i][j] = largestNumberInMatrix;
      }
    }
  }

  HungarianAlgorithm.step1(2);
  console.log("Largest number in matrix: " + largestNumberInMatrix);

  function getLargestNumberInMatrix(matrix) {
    var largestNumberInMatrix = 0;
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      for (var j = 0; j < matrix[i].length; j++) {
        currentNumber = matrix[i][j];
        largestNumberInMatrix = (largestNumberInMatrix > currentNumber) ?
          largestNumberInMatrix : currentNumber;
      }
    }
    return largestNumberInMatrix;
  }
}

HungarianAlgorithm.step3 = function() {
  var smallestNumberInRow = 0;
  var currentNumber = 0;

  for (var i = 0; i < matrix.length; i++) {
    smallestNumberInRow = getSmallestNumberInRow(matrix, i);
    console.log("Smallest number in row[" + i + "]: " + smallestNumberInRow);
    for (var j = 0; j < matrix[i].length; j++) {
      currentNumber = matrix[i][j];
      matrix[i][j] = currentNumber - smallestNumberInRow;
    }
  }

  HungarianAlgorithm.step1(3);

  function getSmallestNumberInRow(matrix, rowIndex) {
    var smallestNumberInRow = matrix[rowIndex][0];
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[rowIndex][i];
      smallestNumberInRow = (smallestNumberInRow < currentNumber) ?
        smallestNumberInRow : currentNumber;
    }
    return smallestNumberInRow;
  }
}

HungarianAlgorithm.step4 = function() {
  var smallestNumberInColumn = 0;
  var currentNumber = 0;

  for (var i = 0; i < matrix.length; i++) {
    smallestNumberInColumn = getSmallestNumberInColumn(matrix, i);
    console.log("Smallest number in column[" + i + "]: " + smallestNumberInColumn);
    for (var j = 0; j < matrix[i].length; j++) {
      currentNumber = matrix[j][i];
      matrix[j][i] = currentNumber - smallestNumberInColumn;
    }
  }

  HungarianAlgorithm.step1(4);

  function getSmallestNumberInColumn(matrix, columnIndex) {
    var smallestNumberInColumn = matrix[0][columnIndex];
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[i][columnIndex];
      smallestNumberInColumn = (smallestNumberInColumn < currentNumber) ?
        smallestNumberInColumn : currentNumber;
    }
    return smallestNumberInColumn;
  }
}

var rowLine = {};
var columnLine = {};
HungarianAlgorithm.step5 = function() {
  var zeroNumberCountRow = 0;
  var zeroNumberCountColumn = 0;

  rowLine = {};
  columnLine = {};
  for (var i = 0; i < matrix.length; i++) {
    zeroNumberCountRow = getZeroNumberCountInRow(matrix, i);
    zeroNumberCountColumn = getZeroNumberCountInColumn(matrix, i);
    if (zeroNumberCountRow > zeroNumberCountColumn) {
      rowLine[i] = i;
      if (zeroNumberCountColumn > 1) {
        columnLine[i] = i;
      }
    } else if (zeroNumberCountRow < zeroNumberCountColumn) {
      columnLine[i] = i;
      if (zeroNumberCountRow > 1) {
        rowLine[i] = i;
      }
    } else {
      if ((zeroNumberCountRow + zeroNumberCountColumn) > 2) {
        rowLine[i] = i;
        columnLine[i] = i;
      }
    }
  }

  var zeroCount = 0;
  for (var i in columnLine) {
    zeroCount = getZeroNumberCountInColumnLine(matrix, columnLine[i], rowLine);
    if (zeroCount == 0) {
      delete columnLine[i];
    }
  }
  for (var i in rowLine) {
    zeroCount = getZeroNumberCountInRowLine(matrix, rowLine[i], columnLine);
    if (zeroCount == 0) {
      delete rowLine[i];
    }
  }

  console.log("horizontal line (row): " + JSON.stringify(rowLine));
  console.log("vertical line (column): " + JSON.stringify(columnLine));

  HungarianAlgorithm.step1(5);

  //if ((Object.keys(rowLine).length + Object.keys(columnLine).length) == matrix.length) {
    // TODO:
    // HungarianAlgorithm.step9();
  //} else {
  //  HungarianAlgorithm.step6();
  //  HungarianAlgorithm.step7();
  //  HungarianAlgorithm.step8();
  //}

  function getZeroNumberCountInColumnLine(matrix, columnIndex, rowLine) {
    var zeroNumberCount = 0;
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[i][columnIndex];
      if (currentNumber == 0 && !(rowLine[i] == i)) {
        zeroNumberCount++
      }
    }
    return zeroNumberCount;
  }

  function getZeroNumberCountInRowLine(matrix, rowIndex, columnLine) {
    var zeroNumberCount = 0;
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[rowIndex][i];
      if (currentNumber == 0 && !(columnLine[i] == i)) {
        zeroNumberCount++
      }
    }
    return zeroNumberCount;
  }

  function getZeroNumberCountInColumn(matrix, columnIndex) {
    var zeroNumberCount = 0;
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[i][columnIndex];
      if (currentNumber == 0) {
        zeroNumberCount++
      }
    }
    return zeroNumberCount;
  }

  function getZeroNumberCountInRow(matrix, rowIndex) {
    var zeroNumberCount = 0;
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[rowIndex][i];
      if (currentNumber == 0) {
        zeroNumberCount++
      }
    }
    return zeroNumberCount;
  }
}

HungarianAlgorithm.step6 = function() {
  var smallestNumberInUncoveredMatrix = getSmallestNumberInUncoveredMatrix(matrix, rowLine, columnLine);
  console.log("Smallest number in uncovered matrix: " + smallestNumberInUncoveredMatrix);

  var columnIndex = 0;
  for (var i in columnLine) {
    columnIndex = columnLine[i];
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[i][columnIndex];
      //matrix[i][columnIndex] = currentNumber + smallestNumberInUncoveredMatrix;
      matrix[i][columnIndex] = "x";
    }
  }

  var rowIndex = 0;
  for (var i in rowLine) {
    rowIndex = rowLine[i];
    for (var i = 0; i < matrix.length; i++) {
      currentNumber = matrix[rowIndex][i];
      //matrix[rowIndex][i] = currentNumber + smallestNumberInUncoveredMatrix;
      matrix[rowIndex][i] = "x";
    }
  }

  HungarianAlgorithm.step1(6);

  function getSmallestNumberInUncoveredMatrix(matrix, rowLine, columnLine) {
    var smallestNumberInUncoveredMatrix = null;;
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      if (rowLine[i]) {
        continue;
      }
      for (var j = 0; j < matrix[i].length; j++) {
        if (columnLine[j]) {
          continue;
        }

        currentNumber = matrix[i][j];
        if (!smallestNumberInUncoveredMatrix) {
          smallestNumberInUncoveredMatrix = currentNumber;
        }

        smallestNumberInUncoveredMatrix =
          (smallestNumberInUncoveredMatrix < currentNumber) ?
          smallestNumberInUncoveredMatrix : currentNumber;
      }
    }
    return smallestNumberInUncoveredMatrix;
  }
}

HungarianAlgorithm.step7 = function() {
  var smallestNumberInMatrix = getSmallestNumberInMatrix(matrix);
  console.log("Smallest number in matrix: " + smallestNumberInMatrix);

  var currentNumber = 0;
  for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j < matrix[i].length; j++) {
      currentNumber = matrix[j][i];
      matrix[j][i] = currentNumber - smallestNumberInMatrix;
    }
  }

  HungarianAlgorithm.step1(7);

  function getSmallestNumberInMatrix(matrix) {
    var smallestNumberInMatrix = matrix[0][0];
    var currentNumber = 0;
    for (var i = 0; i < matrix.length; i++) {
      for (var j = 0; j < matrix[i].length; j++) {
        currentNumber = matrix[i][j];
        smallestNumberInMatrix = (smallestNumberInMatrix < currentNumber) ?
          smallestNumberInMatrix : currentNumber;
      }
    }
    return smallestNumberInMatrix;
  }
}

HungarianAlgorithm.step8 = function() {
  console.log("Step 8: Covering zeroes with Step 5 - 8 until Step 9 is reached");
  HungarianAlgorithm.step5();
}

HungarianAlgorithm.step9 = function(){
  console.log("Step 9...");
}


HungarianAlgorithm.step1(1);
HungarianAlgorithm.step2();
HungarianAlgorithm.step3();
HungarianAlgorithm.step4();
HungarianAlgorithm.step5();
HungarianAlgorithm.step6();
3
répondu jjcosare 2015-04-30 04:20:12

@CMPS réponse échoue sur un certain nombre de graphiques. Je pense que j'ai mis en œuvre une solution qui résout le problème.

j'ai suivi L'article de Wikipedia sur le algorithme hongrois et j'ai fait une implémentation qui semble fonctionner tout le temps. De Wikipedia, voici une méthode pour dessiner le nombre minimum de lignes:

tout d'abord, assignez autant de tâches que possible. Marquer toutes les lignes n'ayant pas d'affectation. Marquer toutes les colonnes(non marquées) ayant des zéros dans la (Les) ligne (s) nouvellement marquée (s). Marquer toutes les lignes ayant des attributions dans les colonnes nouvellement marquées. Répéter l'opération pour toutes les rangées non attribuées.

Voici mon implémentation Ruby:

def draw_lines grid
    #copies the array    
    marking_grid = grid.map { |a| a.dup }

    marked_rows = Array.new
    marked_cols = Array.new

    while there_is_zero(marking_grid) do 
        marking_grid = grid.map { |a| a.dup }

        marked_cols.each do |col|
            cross_out(marking_grid,nil, col)
        end

        marked = assignment(grid, marking_grid)    
        marked_rows = marked[0]
        marked_cols.concat(marked[1]).uniq!

        marking_grid = grid.map { |a| a.dup }

        marking_grid.length.times do |row|
            if !(marked_rows.include? row) then
                cross_out(marking_grid,row, nil)
            end
        end

        marked_cols.each do |col|
            cross_out(marking_grid,nil, col)
        end

    end


    lines = Array.new

    marked_cols.each do |index|
        lines.push(["column", index])
    end
    grid.each_index do |index|
        if !(marked_rows.include? index) then
            lines.push(["row", index])
        end
    end
    return lines
end


def there_is_zero grid
    grid.each_with_index do |row|
        row.each_with_index do |value|
            if value == 0 then
                return true
            end
        end
    end
    return false
end

def assignment grid, marking_grid 
    marking_grid.each_index do |row_index|
        first_zero = marking_grid[row_index].index(0)
        #if there is no zero go to next row
        if first_zero.nil? then
            next        
        else
            cross_out(marking_grid, row_index, first_zero)
            marking_grid[row_index][first_zero] = "*"
        end
    end

    return mark(grid, marking_grid)
end


def mark grid, marking_grid, marked_rows = Array.new, marked_cols = Array.new
    marking_grid.each_with_index do |row, row_index|
        selected_assignment = row.index("*")
        if selected_assignment.nil? then
            marked_rows.push(row_index)
        end
    end

    marked_rows.each do |index|
        grid[index].each_with_index do |cost, col_index|
            if cost == 0 then
                marked_cols.push(col_index)    
            end
        end
    end
    marked_cols = marked_cols.uniq

    marked_cols.each do |col_index|
        marking_grid.each_with_index do |row, row_index|
            if row[col_index] == "*" then
                marked_rows.push(row_index)    
            end
        end
    end

    return [marked_rows, marked_cols]
end


def cross_out(marking_grid, row, col)
    if col != nil then
        marking_grid.each_index do |i|
            marking_grid[i][col] = "X"    
        end
    end
    if row != nil then
        marking_grid[row].map! {|i| "X"} 
    end
end

grid = [
    [0,0,1,0],
    [0,0,1,0],
    [0,1,1,1],
    [0,1,1,1],
]

p draw_lines(grid)
0
répondu KNejad 2017-03-20 13:16:47