fork download
  1. #include <stdio.h>
  2.  
  3. #define VALID(x) ((x) >= 0 && (x) < 3)
  4.  
  5. int arr[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
  6.  
  7. // to detect previous visited cells and eliminate infinite recursion
  8. short vis[3][3] = { 0 };
  9.  
  10. int xtar, ytar; // destination cell
  11. int xsrc, ysrc; // source cell
  12.  
  13. // to move in directions: down, up, right, and left, respectively
  14. const int dirx[] = { 0, 0, 1, -1 };
  15. const int diry[] = { 1, -1, 0, 0 };
  16.  
  17. // temp buffer to print paths
  18. // max size = size of arr + zero termination char
  19. char tmp_path[3 * 3 + 1];
  20.  
  21. void rec(int x, int y, int idx) // idx is used to fill tmp_path
  22. {
  23. int i;
  24. if (vis[y][x]) return; // already visited
  25. tmp_path[idx] = arr[y][x] + '0';
  26. if (x == xtar && y == ytar) // basic case
  27. {
  28. tmp_path[idx + 1] = 0; // put zero char
  29. printf("%s\n", tmp_path); // print path
  30. return;
  31. }
  32. vis[y][x] = 1; // otherwise, mark as visited
  33. for (i = 0; i < 4; ++i) // for each of the 4 directions
  34. if (VALID(y + diry[i]) && VALID(x + dirx[i]))
  35. rec(x + dirx[i], y + diry[i], idx + 1);
  36. vis[y][x] = 0; // reset visited so that can be visited again
  37. }
  38.  
  39. main()
  40. {
  41. // input xtar, ytar, xsrc, ysrc, arr
  42. xtar = 1;
  43. ytar = 2;
  44. xsrc = 0;
  45. ysrc = 0;
  46. rec(xsrc, ysrc, 0);
  47. }
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
1478
1458
14523698
145698
1258
125698
125478
123698
123658
12365478