首页 > 解决方案 > 编写一个程序,测试二维数组的同一行或同一列是否有两个 1

问题描述

我需要编写一个程序,循环遍历一个二维数组,其中元素由 1 或 0 组成,并检查一行或一列中是否有两个 1,然后打印 true,如果我在同一列上找到两个 1或行我可以停在那里(我不需要数1)。

所以我计划为行中的 1 创建一个计数器,为列中的 1 创建一个计数器,如果该计数器高于 1,则循环中断并打印。但是,计数器不会每行或每列重置,所以目前如果它找到任何两个 1,无论它们的位置如何,它都会打印出来。

我尝试在 for 循环的末尾为每个添加一个 rowTotal = 0 & colTotal = 0 但是这样做根本找不到任何 1。

另外,这是针对我的数据结构和算法类的,所以我需要提供一个完整的算法,所以我不想为此使用任何函数。任何有关改进我的代码或解决此问题的更好方法的提示将不胜感激。我可以在 Python 或 Java 中做到这一点。

非常感谢

int[][] board = new int[4][4];



// number to look for
        int findNum = 1;
        // initial total 
        int total = 0;  
        // flag variable to end loop
        boolean found = false;       
        // loops only if found is not 
        for (int i = 0; i < board.length && !found; i++)
        {     
            // resets for each new iteration 
            total = 0;  
            // loops only if found is not 
            for(int j = 0; j < board[i].length && !found; j++)
            {              
                //check row
                if(board[i][j] == findNum) {
                    total++;
                }
                // check column
                if(board[j][i] == findNum) {
                    total++;
                }
                // if more total greater than 1 then end
                if(total > 1) {
                    found = true;
                }
            }

        }

标签: javaalgorithmloopsfor-loopmultidimensional-array

解决方案


内部循环更改 if 使用条件colTotal而不是rowTotal

 if (colTotal > 1) {
   System.out.println("2 lying on col");
   break;
 } 

请记住,这break不会破坏外循环,因此您需要一个标志,例如。

 boolean found = false; // outside loops

当您打印和中断时,只需分配true

 found = true; // before break inside inner loop, adjecent to print statement

现在使用这个标志来检查作为外循环内的第一条语句

 if (found) {
    break;
 }

或者只是你可以将它作为外循环中的条件

 for (int i = 0; i < board.length && !found; i++)

推荐阅读