H.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include<iostream>
  2. #include<cstring>
  3. #include<queue>
  4. using namespace std;
  5. int map[51][51],t[51][51];
  6. long long s[51][51];
  7. int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
  8. int n,m;
  9. struct pp
  10. {
  11. int x,y;
  12. };
  13. queue<pp> que;
  14. int flag[99][99];
  15. void bfs()
  16. {
  17. pp a,b;
  18. int dx,dy,i,spend;
  19. a.x=n-1;a.y=m-1;
  20. t[n-1][m-1]=map[n-1][m-1];
  21. que.push(a);
  22. while(!que.empty())
  23. {
  24. b=que.front();
  25. que.pop();
  26. for(i=0;i<4;i++)
  27. {
  28. dx=b.x+dir[i][0];
  29. dy=b.y+dir[i][1];
  30. if(dx>=0&&dx<n&&dy>=0&&dy<m)
  31. {
  32. spend=t[b.x][b.y]+map[dx][dy];
  33. if(t[dx][dy]==-1||spend<t[dx][dy])
  34. {
  35. a.x=dx;
  36. a.y=dy;
  37. t[dx][dy]=spend;
  38. que.push(a);
  39. }
  40. }
  41. }
  42. }
  43. }
  44. long long dfs(int x,int y)
  45. {
  46. int i;
  47. if(s[x][y]>-1)
  48. return s[x][y];
  49. if(x==n-1&&y==m-1)
  50. return 1;
  51. flag[x][y]++;
  52. s[x][y]=0;
  53. for(i=0;i<4;i++)
  54. {
  55. int xx=x+dir[i][0];
  56. int yy=y+dir[i][1];
  57. if(xx>=0&&xx<n&&yy>=0&&yy<m)
  58. {
  59. if(t[x][y]>t[xx][yy])
  60. {
  61. s[x][y]+=dfs(xx,yy);
  62. }
  63. }
  64. }
  65. return s[x][y];
  66. }
  67. int main()
  68. {
  69. int i,j;
  70. while(cin>>n>>m)
  71. {
  72. for(i=0;i<n;i++)
  73. for(j=0;j<m;j++)
  74. {
  75. cin>>map[i][j];
  76. t[i][j]=-1;
  77. }
  78. while(!que.empty()) que.pop();
  79. memset(s,-1,sizeof(s));
  80. memset(flag,0,sizeof(flag));
  81. bfs();
  82. dfs(0,0);
  83. cout<<s[0][0]<<endl;
  84. }
  85. return 0;
  86. }