Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #define INF (1<<29)
- using namespace std;
- int dx[] = {0, 0, 1,-1};
- int dy[] = {1,-1, 0, 0};
- struct grafo {
- vector< string > ady;
- vector<vector<int>> dist;
- priority_queue< pair<int, pair<int,int> > > pq;
- int n, m, p;
- void leer ()
- {
- cin>>n>>m;
- ady.resize(n);
- dist = vector< vector<int> > (n, vector<int> (m, INF) );
- for(int x=0; x<n; x++)
- for(int y=0; y<m; y++)
- cin>>ady[x][y];
- cin>>p;
- }
- bool visitable (int x, int y)
- {
- if ((0<=x && x<n) && (0<=y && y<m))
- if(ady[x][y]!='#')
- return true;
- return false;
- }
- void iniciar (int x, int y)
- {
- if ( visitable( x,y ) )
- {
- dist[x][y] = ady[x][y]-'0';
- pq.push( {ady[x][y], {x,y} } );
- }
- }
- void dijkstra ()
- {
- for(int x=0; x<n; x++)
- {
- iniciar(x, 0 );
- iniciar(x, m-1);
- }
- for(int y=0; y<m; y++)
- {
- iniciar(0 , y);
- iniciar(n-1, y);
- }
- while( pq.size() )
- {
- int x = pq.top().second.first;
- int y = pq.top().second.second;
- pq.pop();
- for(int i=0; i<4; i++)
- {
- int vx = x+dx[i];
- int vy = y+dy[i];
- int costo = ady[vx][vy]-'0';
- if ( visitable(vx,vy) )
- {
- if ( dist[x][y]+costo < dist[vx][vy] )
- {
- dist[vx][vy] = dist[x][y]+costo;
- pq.push( {-dist[vx][vy], {vx,vy} } );
- }
- }
- }
- }
- /**for(int x=0; x<n; x++)
- {
- for(int y=0; y<m; y++)
- cout<<ady[x][y]<<" ";
- cout<<endl;
- }
- cout<<endl;*/
- for(int x=0; x<n; x++)
- {
- for(int y=0; y<m; y++)
- {
- if (ady[x][y]=='#')
- cout<<"# ";
- else if (dist[x][y]==INF)
- cout<<"N0 ";
- else if (dist[x][y]<10)
- cout<<dist[x][y]<<" ";
- else cout<<dist[x][y]<<" ";
- }
- cout<<endl;
- }
- cout<<endl;
- int x, y;
- for(int i=0; i<p; i++)
- {
- cin>>x>>y;
- cout<<x<<" "<<y<<" -> ";
- if(dist[x-1][y-1]==INF)
- cout<<"NO"<<endl;
- else cout<<dist[x-1][y-1]<<endl;
- }
- }
- };
- int main()
- {
- grafo g;
- g.leer();
- g.dijkstra();
- return 0;
- }
- /*
- 8 15
- 0 # # # # # # # # # # # # # #
- 1 1 6 8 8 8 8 # 1 8 8 8 2 2 #
- # 1 # # # # # # 1 # # # # 2 #
- # 1 2 2 2 2 0 8 1 2 2 2 2 2 #
- # 1 # # # # 0 # 1 # # # # # #
- # 1 # # 5 # 0 1 1 # 9 9 # 1 #
- # 3 3 # 5 # # # # # 9 # # 1 #
- # # # # 5 # # # # # 9 # # # #
- 4
- 7 3
- 4 8
- 2 13
- 7 13
- */
Advertisement
Add Comment
Please, Sign In to add comment