【发布时间】:2020-03-11 16:25:11
【问题描述】:
我需要编写一个程序,循环遍历一个二维数组,其中元素由 1 或 0 组成,并检查一行或一列中是否有两个 1,如果找到两个 1,则打印 true在同一列或同一行上,我可以停在那里(我不需要数 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;
}
}
}
【问题讨论】:
-
在上面发布了更正的代码。因为这是针对 DSA 课程的,所以我无法使用任何其他功能,老师希望它在两个循环中使用。我只需要添加 if(board[j][i] == findNum) {total++;} 感谢他们帮助我清理代码并找到答案的所有答案。尽管如此,我还是花了几个小时才找到这个。
标签: java algorithm loops for-loop multidimensional-array