Java中名人算法的暴力解决方案

时间:2017-12-04 03:03:43

标签: java

在N人的聚会中,每个人都只知道一个人。这样的人可能出现在党内,如果是的话,他不认识党内的任何人。我们只能问诸如“A知道B吗?”之类的问题。 “。在最少的问题中找到陌生人(名人)。

我知道这可以通过队列或堆栈来解决,但我想首先用蛮力来解决它来练习我的工作。我的尝试循环遍历矩阵以查看哪一行具有全0。现在我如何仔细检查该行是否包含一个0和其余的1?这是我的代码:

public static int[][] matrix = {{0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 0, 0},
                                {0, 0, 1, 0}};

public static void main(String[] args) {
    if(knowsCeleb() > 0){
        System.out.println(knowsCeleb() + " is the celebrity.");
    }else{
        System.out.println("There is no celebrity.");
    }
}

public static int knowsCeleb(){
    int count = 0;

    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[i].length; j++){

            if(matrix[i][j] == 0){
                count++;
            }else{
                count = 0;
                break;
            }
        }

        if(count == matrix[i].length){
            return (i+1);
        }
    }
    return 0;
}

在这种情况下,第三行是名人,因为它不知道任何人(行中的0)但每个人都知道它(列中的1)。如何修复我的代码,以便它检查正确的列是否包含1和1。例如,此输入:

 public static int[][] matrix = {{0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 0, 0}};

打印出4是名人,即使没有人知道4(最后一栏没有1)。如何执行第二次检查以确认它实际上是名人?请帮忙!

1 个答案:

答案 0 :(得分:1)

如果我正确理解目标,似乎您已经描述了确认矩阵条目必须满足的条件:“仔细检查正确的列是否包含1和0。”所以我们可以创建一个方法,明确检查列包含1和0:

public static boolean confirm(int column){
    int zeros = 0;
    int ones = 0;
    column = column - 1; // java indexes from zero, so we decrement column

    boolean confirmed = false; // set the result initially unconfirmed

    // for each row
    for(int i = 0; i < matrix[column].length; i++){
        // if the value in the specified column is zero
        if (matrix[i][column] == 0)
            // add to zeros
            zeros++;
        // otherwise if the value in the specified column is one
        else if (matrix[i][column] == 1)
            // add to ones
            ones++;
    }

    // the condition we want to double check 
    // "correct column contains 1s and one zero"
    if (zeros == 1 && ones == 3){
        confirmed = true;  // confirm
    }
    return confirmed; 
}

现在我们已经有了这个方法,请从main调用它:

System.out.println("Confirm " + knowsCeleb() + ": " + confirm(knowsCeleb()));

输出如下内容:

3 is the celebrity.
Confirm 3: true