I was wondering why my code won't execute the printf
?
So the code input consists of T
, the number of testcases. For each case, there are N
, M
, number of rows and columns in someone's house plan. Then, N
lines follow, which consist of M
characters describing his/her house plan information.
#include<stdio.h>
char image[1000][1000];
int row,col;
int tileCount = 0;
bool valid(int i,int j)
{
if(i<0 || i>=row || j<0 || j>=col)
return false;
else
return true;
}
void floodFill(int x, int y)
{
if(valid(x,y) == false)
return;
if(image[x][y] == '#')
return;
if(image[x][y] == '.'){
image[x][y] = '#';
tileCount ;
}
floodFill(x-1,y);
floodFill(x 1,y);
floodFill(x,y-1);
floodFill(x,y 1);
}
int main()
{
int t;
scanf("%d", &t);
for(int i=1; i<=t; i ){
tileCount = 0;
int x, y;
scanf("%d %d", &row, &col);
for(int k=0;k<row;k )
{
for(int j=0;j<col;j )
{
scanf("%d", &image[k][j]);
//getchar();
if(image[k][j] == 'S'){
x = k;
y = j;
}
}
getchar();
}
floodFill(x,y);
printf("Case #%d: %d\n", i, tileCount);
}
return 0;
}
Output should be expressed in format
Case #X: Y
Where X is number of floors (tiles) to be replaced in Xth case.
I tried many things, but I still can't solve the problem.
CodePudding user response:
The first thing to learn is to set your compiler to a high warning level and to treat all warnings as errors. For instance for gcc
you should compile using the options -Wall -Wextra -Werror
.
That would have told about a type mismatch in the code scanf("%d", &image[k][j]);
as you scan for intergers (%d
) but store the result in a char-array.
Further, it would tell that x
and y
might be uninitialized (i.e. in case the user never gave 'S'
as input).
"Correct" compiler options would have helped detecting these issues.
Now for the floodFill
function imagine that you call it with (0, 0)
and that image[0][0]
and image[1][0]
contains values different from both '#'
and '.'
.
That will - in principle - lead to the follwing code:
floodFill(0, 0)
{
....
floodFill(-1, 0);
floodFill(1, 0);
floodFill(0, -1);
floodFill(0, 1);
}
The call floodFill(-1, 0)
will just return as it's not valid but for floodFill(1, 0);
the code will be:
floodFill(1, 0)
{
....
floodFill(0, 0); <------ ups, calling with (0, 0) again
floodFill(2, 0);
floodFill(1, -1);
floodFill(1, 1);
}
Notice how this leads to a new call of floodFill(0, 0)
. In other words - you have created an endless loop like:
floodFill(0, 0) -> floodFill(1, 0) -> floodFill(0, 0) -> floodFill(1, 0) -> ...
So nothing will be printed and the program will (most likely) crash due to a stack overflow.