我试图解决的问题是:
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows:
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.
Please output the maximum number of cake cells that the cakeminator can eat.
The first line of input contains two integers r and c (2 ≤ r, c ≤ 10), denoting the number of rows and the number of columns of the cake. The next r lines each contains c characters — the j-th character of the i-th line denotes the content of the cell at row i and column j, and is either one of these:
'.' character denotes a cake cell with no evil strawberry;
'S' character denotes a cake cell with an evil strawberry.
Output the maximum number of cake cells that the cakeminator can eat.
这是一个应该生成 8
的示例输入:
3 4
S...
....
..S.
我的代码给出12
:
#include <stdio.h>
int main(void) {
int r, c;
scanf("%d %d", &r, &c);
int cake[r][c];
int i, j, cnt=0, cou=0, a=0, b=0, cell=0;
getchar(); //reject "\n"
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
scanf("%c", &cake[i][j]);
}
getchar();
}
// debug
// printf("%c\n", cake[0][0]);
// printf("%c\n", cake[0][1]);
// printf("%c\n", cake[0][2]);
// printf("%c\n", cake[0][3]);
// printf("%c\n", cake[2][2]);
for(i=0;i<r; i++) {
for(j=0;j<c;j++) {
cnt++;
if(cake[i][j]=='S') {
cnt=0;
break;
}
}
if(cnt>0) {
a++;
}
}
for(j=0;j<c;j++) {
for(i=0;i<r;i++) {
cou++;
if(cake[i][j]=='S') {
cou=0;
break;
}
}
if(cou>0) {
b++;
}
}
cell=cnt + cou - a*b;
printf("%d", cell);
return 0;
}
通过调试,发现if(cake[i][j] == 'S')
错误,但不知道原因。
最佳答案
更正代码,更改通过“<---change”通知
#include <stdio.h>
int main(void) {
int r, c;
scanf("%d %d", &r, &c);
char cake[r][c]; <--- Change
int i, j, cnt=0, cou=0, a=0, b=0, cell=0;
//reject "\n" <--- Change
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
scanf("%c", &cake[i][j]);
}
<--- Change
}
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
cnt++;
if(cake[i][j]=='S') {
cnt=0;
break;
}
}
if(cnt>0) {
a++;
}
}
for(j=0;j<c;j++) {
for(i=0;i<r;i++) {
cou++;
if(cake[i][j]=='S') {
cou=0;
break;
}
}
if(cou>0) {
b++;
}
}
cell=cnt + cou - a*b;
printf("%d", cell);
return 0;
}
关于c - 我的算法代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26607114/