fork download
  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<vector>
  4. #include<time.h>
  5. #include<stdlib.h>
  6. #include<set>
  7. using namespace std;
  8.  
  9.  
  10. namespace sortspace{
  11.  
  12. int input[10][10];
  13. int n,m;
  14.  
  15. struct myComp
  16. {
  17. bool operator()(const int& a,const int& b) const{
  18. int ai=a/m,aj=a%m;
  19. int bi=b/m,bj=b%m;
  20. if(input[ai][aj]!=input[bi][bj])
  21. return input[ai][aj]<input[bi][bj];
  22. else
  23. return a<b;
  24. }
  25. };
  26. void twoDto1D()
  27. {
  28. set<int,myComp> st;
  29. st.insert(0);
  30. int top,i,j;
  31. while(!st.empty())
  32. {
  33. top=*(st.begin());
  34. //cout<<top<<"\n";
  35. st.erase(st.begin());
  36. i=top/m;
  37. j=top%m;
  38. cout<<input[i][j]<<" ";
  39. if(i+1<n){
  40. //cout<<(i+1)*m+j<<"\n";
  41. st.insert((i+1)*m+j);
  42. }
  43. if(j+1<m){
  44. st.insert(i*m+j+1);
  45. //cout<<(i*m+j+1)<<"\n";
  46. }
  47.  
  48. }
  49. }
  50.  
  51.  
  52. };
  53.  
  54. int main()
  55. {
  56. using namespace sortspace;
  57. n=4,m=3;
  58. for(int i=0;i<n;i++)
  59. for(int j=0;j<m;j++)
  60. cin>>input[i][j];
  61. twoDto1D();
  62. }
  63.  
Success #stdin #stdout 0s 3432KB
stdin
1 4 7
3 6 9
5 8 10
7 12 14
stdout
1 3 4 5 6 7 7 8 9 10 12 14