[英]Finding the first row of zeros n x n array in C
I have some pseudocode that finds the first all-zero row in an nxm matrix: 我有一些伪代码可以找到nxm矩阵中的第一个全零行:
int first_zero_row = -1; /* none */
int i, j;
for(i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (A[i][j]) goto next;
}
first_zero_row = i;
break;
next: ;
}
While this should work, I don't think using a goto statement is the best way to go. 尽管这应该可行,但我认为使用goto语句不是最好的方法。 I'm not very familiar with C but my goal is to have the code as well structured in C as possible. 我对C不太熟悉,但是我的目标是使代码在C中尽可能地结构化。 Would this be the best way to go about it, or is there a faster or more general way? 这是解决问题的最佳方法,还是有一种更快或更通用的方法?
Just set first_zero_row
only when the inner loop ran to completion, 仅在内部循环运行完成时才设置first_zero_row
,
int first_zero_row = -1; /* none */
int i, j;
for(i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (A[i][j]) break;
}
if (j == n) {
first_zero_row = i;
break;
}
}
if you want to avoid the goto
. 如果您想避免goto
。
Place break;
放假break;
statement instead of goto statement. 语句而不是goto语句。 Set a boolean flag and check for the flag and if the flag is true, then break again from outer for loop too. 设置一个布尔标志并检查该标志,如果该标志为真,则也从外部for循环再次中断。 Something like this - 像这样-
bool nonZeroFlag = true;
for(i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (A[i][j]){
nonZeroFlag = false;
break;
}
}
if (nonZeroFlag) {
first_zero_row = i;
break;
}
nonZeroFlag = true;
}
int first_zero_row = -1; /* none */
int i, j;
for(i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (A[i][j] != 0){
first_zero_row = i;
}
}
break;
next: ;
}
how about this? 这个怎么样?
Here is one with no break
or goto
:) 这是一个没有break
或goto
:)
int zero_count = -1; /* none */
i = j = 0;
for(i=0; i < n && (zero_count != n); i++) {
for (j=0; j < n && (A[i][j] == 0); j++) {
zero_count = j + 1;
}
}
if(i < 10)
printf("First Zero row is %d\n",i);
else
printf("Nop! Not today!\n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.