gpt4 book ai didi

java - 编写一个程序,测试二维数组中是否有两个 1 位于同一行或同一列

转载 作者:行者123 更新时间:2023-11-30 01:44:00 26 4
gpt4 key购买 nike

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

所以我计划为行中的 1 创建一个计数器,为列中的 1 创建一个计数器,如果该计数器超过 1,则循环中断并打印。然而,计数器不会按行或列重置,因此目前如果它找到任何两个 1,无论其位置如何,它都会打印。

我尝试在每个循环的末尾添加 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;
}
}

}

最佳答案

内部循环内部更改 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++)

关于java - 编写一个程序,测试二维数组中是否有两个 1 位于同一行或同一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com