fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. static void press(int codeLenSoFar, int x, int y);
  4.  
  5. #define PAD_WIDTH 3
  6. #define PAD_HEIGHT 3
  7. #define MIN_CODE_LEN 1 /* >= 1 */
  8. #define MAX_CODE_LEN (PAD_WIDTH * PAD_HEIGHT)
  9.  
  10. typedef struct {
  11. int dx;
  12. int dy;
  13. } direction;
  14.  
  15. static const direction directions[] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}
  16. ;
  17.  
  18. static unsigned long nCodes[MAX_CODE_LEN - MIN_CODE_LEN + 1] = {0};
  19. static int pad[PAD_WIDTH][PAD_HEIGHT] = {{0}};
  20.  
  21. int main(void) {
  22. int len, x, y;
  23. unsigned long sum;
  24.  
  25. for (y = 0; y < PAD_HEIGHT; ++y) {
  26. for (x = 0; x < PAD_WIDTH; ++x) {
  27. press(0, x, y);
  28. }
  29. }
  30. sum = 0;
  31. for (len = MIN_CODE_LEN; len <= MAX_CODE_LEN; ++len) {
  32. if (printf("%d long: %lu\n", len, nCodes[len - MIN_CODE_LEN]) <
  33. 0) exit(EXIT_FAILURE);
  34. sum += nCodes[len - MIN_CODE_LEN];
  35. }
  36. if (printf("sum: %lu\n", sum) < 0) exit(EXIT_FAILURE);
  37. return EXIT_SUCCESS;
  38. }
  39.  
  40. static void press(int codeLenSoFar, int x, int y) {
  41. int i, nextX, nextY;
  42.  
  43. if (++codeLenSoFar >= MIN_CODE_LEN) {
  44. ++nCodes[codeLenSoFar - MIN_CODE_LEN];
  45. }
  46. pad[x][y] = 1;
  47. if (codeLenSoFar < MAX_CODE_LEN) {
  48. for (i = 0; i < (int) (sizeof directions / sizeof *directions);
  49. ++i) {
  50. nextX = x + directions[i].dx;
  51. nextY = y + directions[i].dy;
  52. if (nextX >= 0 && nextX < PAD_WIDTH && nextY >= 0 && nextY <
  53. PAD_HEIGHT && !pad[nextX][nextY]) {
  54. press(codeLenSoFar, nextX, nextY);
  55. }
  56. }
  57. }
  58. pad[x][y] = 0;
  59. }
  60.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
1 long: 9
2 long: 24
3 long: 44
4 long: 80
5 long: 104
6 long: 128
7 long: 112
8 long: 112
9 long: 40
sum: 653