Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef pair<int,int> ii;
- #define OO 0x7fffffff
- #define S second
- #define F first
- int dx[] = {1 ,-1 ,0 , 0};
- int dy[] = {0 , 0 ,1 ,-1};
- const int N = 1e3 + 3e1;
- vector< vector< ii > > kColorIdx;
- int Grid[N][N];
- int n ,m ,k;
- inline bool isValid(int i ,int j) {
- return (i > 0 && j > 0 && i <= n && j <= m && Grid[i][j] != 0);
- }
- int BFS( ii Start , ii End ) {
- vector< vector<int> > Dist(n + 1 , vector<int>(m + 1 ,OO) );
- Dist[ Start.F ][ Start.S ] = 0;
- queue< ii > Q; Q.push( Start );
- while( !Q.empty() ) {
- ii front = Q.front(); Q.pop();
- int i = front.F , j = front.S;
- int Color = Grid[i][j];
- for(int x = 0 ; x < (int)kColorIdx[ Color ].size() ; x++) {
- ii idx = kColorIdx[ Color ][ x ];
- Dist[ idx.F ][ idx.S ] = Dist[i][j];
- for(int move = 0 ; move < 4 ; move ++) {
- int newI = idx.F + dx[ move ];
- int newJ = idx.S + dy[ move ];
- if( isValid(newI ,newJ) && Dist[ newI ][ newJ ] == OO && Grid[ newI ][ newJ ] != Color ) {
- Dist[ newI ][ newJ ] = Dist[ idx.F ][ idx.S ] + 1;
- Q.push( ii(newI ,newJ) );
- }
- }
- }
- }
- return Dist[ End.F ][ End.S ];
- }
- int main()
- {
- scanf("%d%d%d" ,&n ,&m ,&k);
- kColorIdx.assign(k + 1 ,vector<ii>());
- ii stIdx = ii(0 ,0) ,edIdx = ii(0 ,0);
- for(int i = 1 ; i <= n ; i++){
- for(int j = 1 ; j <= m ; j++){
- scanf("%d" ,&Grid[i][j]);
- int Color = Grid[i][j];
- kColorIdx[ Color ].push_back( ii(i ,j) );
- if( Color == 1 ) stIdx = ii(i ,j);
- if( Color == k ) edIdx = ii(i ,j);
- }
- }
- printf( "%d" ,BFS(stIdx ,edIdx) );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement