fork download
  1. #include <stdio.h>
  2. #include <queue>
  3. #include <map>
  4. #include <string>
  5. #include <stdlib.h>
  6. #define SWAP(a, b) a^=b; b^=a; a^=b;
  7. using namespace std;
  8.  
  9. void shiftBlock(string s, int a, int b);
  10. queue<int> q;
  11. map<string, int> m;
  12.  
  13. int main() {
  14. //int resultState[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
  15. int start = 0;
  16.  
  17. for(int i=100000000; i>=1; i/=10){
  18. int x;
  19. scanf("%d ", &x);
  20. if(x==0) x=9;
  21. start += i*x;
  22. }
  23.  
  24. q.push(start);
  25. m[to_string(start)] = 0;
  26.  
  27. while(!q.empty()){
  28. string now = to_string(q.front());
  29. q.pop();
  30.  
  31. for(int i=0; i<9; i++){
  32. if(now[i] != '9') continue;
  33.  
  34. switch(i){
  35. case 0:
  36. shiftBlock(now, i, i+1);
  37. shiftBlock(now, i, i+3);
  38. break;
  39. case 1:
  40. shiftBlock(now, i, i-1);
  41. shiftBlock(now, i, i+3);
  42. shiftBlock(now, i, i+1);
  43. break;
  44. case 2:
  45. shiftBlock(now, i, i-1);
  46. shiftBlock(now, i, i+3);
  47. case 3:
  48. shiftBlock(now, i, i+3);
  49. shiftBlock(now, i, i+1);
  50. shiftBlock(now, i, i-3);
  51. case 4:
  52. shiftBlock(now, i, i+1);
  53. shiftBlock(now, i, i-1);
  54. shiftBlock(now, i, i+3);
  55. shiftBlock(now, i, i-3);
  56. case 5:
  57. shiftBlock(now, i, i-1);
  58. shiftBlock(now, i, i+3);
  59. shiftBlock(now, i, i-3);
  60. case 6:
  61. shiftBlock(now, i, i-3);
  62. shiftBlock(now, i, i+1);
  63. case 7:
  64. shiftBlock(now, i, i+1);
  65. shiftBlock(now, i, i-1);
  66. shiftBlock(now, i, i-3);
  67. case 8:
  68. shiftBlock(now, i, i-1);
  69. shiftBlock(now, i, i-3);
  70. }
  71. }
  72.  
  73. }
  74. printf("%d", m["123456789"]);
  75. return 0;
  76. }
  77.  
  78. void shiftBlock(string s, int a, int b){
  79. string temp = s;
  80. SWAP(temp[a], temp[b]);
  81. q.push( atoi(temp.c_str()));
  82. m[temp] = m[s] + 1;
  83. }
  84.  
Runtime error #stdin #stdout #stderr 0s 80768KB
stdin
1 0 3
4 2 5
7 8 6
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc