Triton
Triton

Reputation: 13

Where to put printf for output

My program is working fine, but when there is no path through the maze, I want to output "There is no path." But right now, if there is no path, I get nothing from output. Can you help me with this?

int A[4][4] = {
   1,1,0,1,
   1,0,1,0,
   1,0,1,0,
   0,0,1,1
};

int path[4][4] ={
  0,0,0,0,
  0,0,0,0,
  0,0,0,0,
  0,0,0,0
};
int findPath(int i, int j, int n){
  if (i == n-1 && j == n-1){
    path[i][j] = 1;
    return 1;
  }
  if (A[i][j] == 1) {
    path[i][j] = 1;
    if (findPath(i, j+1, n)==1) return 1;
    if (findPath(i+1, j, n)==1) return 1;
    path[i][j] = 0;
  }
  return 0;
}


int main() {
  int i,j;
  findPath(0,0,4);
  for (i = 0; i < 4; i++)
      for (j = 0; j < 4; j++)
          if (path[i][j])
              printf("(%d,%d)-->\n",i,j);
  printf("\n");
  return 0;
}

Upvotes: 1

Views: 75

Answers (2)

jbulatek
jbulatek

Reputation: 164

It's a bit too late in my local time, to think about if this code works, so I will just assume it works as you intended. Then I think you are looking for this:

[...]
int main() {
  int i,j;
  if(findPath(0,0,4));
[...]
  else
    printf("There's no path");
  return 0;
}

I would stronly advise to read about graphs though.

Upvotes: 0

Isaiah
Isaiah

Reputation: 680

You get nothing from the output because you only print stuff if a path exists. Thus, your question is essentially, "How do I determine if there is no path through the maze?"

One easy method is to check the opposite of this condition: if there is ever a point in the grid where one can travel through the maze, then a path must exist. Using this idea leads to the following strategy: 1) Assume a path does not exist 2) Check if there is ever a point where a path does exist 3) Check your assumption once more at the end. This leads to the following code:

int no_path = 1; // 1) First assume there is no path.
                 // It may be preferable to include <stdbool.h> and
                 // use the provided boolean type.
for (i = 0; i < 4; i++) {
  for (j = 0; j < 4; j++) {
    if (path[i][j]) { // 2) Loop through and check if there is actually a path.
      printf("(%d,%d)-->\n",i,j);
      no_path = 0; // 2) Aha, there is a path after all!
    }
  }
}
if (no_path) { // 3) Check if no path exists once more at the end.
  printf("No path exists!\n");
}

Upvotes: 2

Related Questions