I'm working on this problem(Uva227).I've almost received correct results when I test the cases, but I've met a problem. I used function gets() to get a line from standard input, and store it in a[0]. but after the first input matrix, a[0] never changes anymore. What's wrong with it?
P.S. In Puzzle #2(i.e., the second input matrix), a[0] didn't changed, so I got a wrong answer. But if I put it first, it returned a correct output. So I think the algorithm is correct, but something went wrong when reading the first line.
English is not my native language; please excuse my syntax errors.
#include <stdio.h>
#include <string.h>
char a[5][5];
int main(){
int _case = 1;
char c;
while(gets(a[0])){//Please focus on this line;it seems that a[0] never changed since first reading.
if(a[0][0] == 'Z') break;
int blank_i, blank_j;
for(int i = 0; i < 5; i++){
if(i) gets(a[i]);
for(int j = 0; j < 5; j++){
if(a[i][j] == ' '){
blank_i = i;
blank_j = j;
}
}
}
bool flag = true;
int i = 0;
while((c = getchar()) != '0'){
switch(c){
case 'A':
a[blank_i][blank_j] = a[blank_i - 1][blank_j];
a[--blank_i][blank_j] = ' '; break;
case 'B':
a[blank_i][blank_j] = a[blank_i + 1][blank_j];
a[++blank_i][blank_j] = ' '; break;
case 'L':
a[blank_i][blank_j] = a[blank_i][blank_j - 1];
a[blank_i][--blank_j] = ' '; break;
case 'R':
a[blank_i][blank_j] = a[blank_i][blank_j + 1];
a[blank_i][++blank_j] = ' '; break;
default: break;
}
}
//add a getchar() here will fix the problem.
printf("Puzzle #%d:\n", _case);
if(blank_i < 0 || blank_i > 4 || blank_j < 0 || blank_j > 4)
printf("This puzzle has no final configuration.\n");
else{
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
printf("%c ", a[i][j]);
}
printf("\n");
}
}
printf("\n");
_case++;
}
return 0;
}
You've misdiagnosed the problem. It's not the case that "after the first input matrix, a[0] never changes anymore." The actual problem is that after you read the
'0'
that ends the list of moves, there's a newline before the next puzzle begins. Your code doesn't take this into account, and so treats the newline as the first character of the first line of the next puzzle. Fix it by swallowing this newline before getting back to the beginning of thewhile
loop.Aside: Some commenters pointed out that you shouldn't use
gets
. They're 100% right, but it's not related to this problem, and switching away from it won't fix this.