c语言 - 矩阵中不断增长的子字符串的长度



给定一个方阵,例如找到正在增长的子字符串的长度。

matrix     |      result       because of
5          |
1 2 3 4 5  |
2 5 2 5 9  |    
7 8 9 0 1 -->       5     -->   1 2 3 4 5
0 0 0 0 0  |
2 3 6 1 2  |

我尝试将a[i][j]a[i][j+1]进行比较并增加计数器,但我认为我的问题是当程序在最终元素上并且它不会增加计数器时。 这里有我的代码:

int main(){
int n;
scanf("%d",&n);
int i,j,a[n][n];
for(i = 0;i < n;i++){
for(j = 0;j <n;j++){
scanf("%d",&a[i][j]);
}
}
int max=-9999;
int counter;
for(i = 0;i < n;i++){
counter=0;
for(j = 0;j <n;j++){
if(a[i][j]<a[i][j+1]){
counter++;
}
if(counter>max){
max = counter;
}
}
}
printf("%d",max);
return 0;
}

对于初学者来说,由于指数范围不能为负,因此将变量max声明为负值是没有意义的

int max=-9999;

它至少可以像

int max = 0;

在此 if 语句中

if(a[i][j]<a[i][j+1]){

ij由于表达式a[i][j+1]而等于n - 1时,可以访问超出分配数组的内存。

还有这个如果语句

if(counter>max){
max = counter;
}

应移出内部 if 语句。

并且变量计数应该在外循环内声明

您可以通过以下方式重写内部 for 循环

int counter=1;
for(j = 1;j <n;j++){
if(a[i][j-1]<a[i][j]){
counter++;
}
}
if(counter>max){
max = counter;
}

最新更新