fork(3) download
  1. #include <stdio.h>
  2.  
  3. #define MAX 21
  4. #define MAXMASK 1025
  5. #define INF 100000
  6.  
  7. int r, c, dirty;
  8. char s[MAX][MAX];
  9. int dp[MAX][MAX][MAXMASK];
  10.  
  11. int getMin(int a, int b) {return (a < b ? a : b);}
  12.  
  13. int bfs(int x, int y, int mask) {
  14. if (s[x][y] == 'x') return INF;
  15. if (s[x][y] >= 'a' && s[x][y] <= 'n') {
  16. int dig = s[x][y]-'a';
  17. mask |= (1<<dig);
  18. }
  19. if (mask == dirty) return 0;
  20. if (dp[x][y][mask] >= 0) return dp[x][y][mask];
  21. if (dp[x][y][mask] == -2) return INF;
  22. int min = INF;
  23. dp[x][y][mask] = -2;
  24. if (x > 0) min = getMin(min, bfs(x-1, y, mask));
  25. if (y > 0) min = getMin(min, bfs(x, y-1, mask));
  26. if (x < r-1) min = getMin(min, bfs(x+1, y, mask));
  27. if (y < c-1) min = getMin(min, bfs(x, y+1, mask));
  28. if (min != INF) min++;
  29. dp[x][y][mask] = min;
  30. return min;
  31. }
  32.  
  33. int main(void) {
  34. int ans, sx, sy, i, j, k;
  35. while (1) {
  36. scanf("%d %d", &c, &r);
  37. if (c == 0) break;
  38. dirty = 0;
  39. for (i=0; i<r; i++) scanf("%s", s[i]);
  40. for (i=0; i<r; i++) {
  41. for (j=0; j<c; j++) {
  42. if (s[i][j] == '*') {
  43. s[i][j] = 'a'+dirty;
  44. dirty++;
  45. } else if (s[i][j] == 'o') sx = i, sy = j;
  46. }
  47. }
  48. dirty = (1<<dirty) - 1;
  49. for (i=0; i<MAX; i++) {
  50. for (j=0; j<MAX; j++) {
  51. for (k=0; k<MAXMASK; k++) dp[i][j][k] = -1;
  52. }
  53. }
  54. ans = bfs(sx, sy, 0);
  55. if (ans >= INF) printf("-1\n");
  56. else printf("%d\n", ans);
  57. }
  58. return 0;
  59. }
Success #stdin #stdout 0s 3880KB
stdin
7 5
.......
.o...*.
.......
.*...*.
.......
15 13
.......x.......
...o...x....*..
.......x.......
.......x.......
.......x.......
...............
xxxxx.....xxxxx
...............
.......x.......
.......x.......
.......x.......
..*....x....*..
.......x.......
10 10
..........
..o.......
..........
..........
..........
.....xxxxx
.....x....
.....x.*..
.....x....
.....x....
0 0
stdout
8
49
-1