解いた問題

7/13/2012

SRM440 Div2 Medium

500

パスをたどればいい



  1. const int H = 50 + 1;  
  2. const int W = 50 + 1;  
  3. pair<intint> path[H][W];  
  4.   
  5. class MazeWanderingEasy {  
  6. public:  
  7.   int decisions(vector <string> maze)  
  8.   {  
  9.     const int h = maze.size();  
  10.     const int w = maze[0].size();  
  11.   
  12.     pair<intint> start, goal;  
  13.     for (int i = 0; i < h; ++i) {  
  14.       for (int j = 0; j < w; ++j) {  
  15.         if (maze[i][j] == 'M') start = make_pair(i, j);  
  16.         if (maze[i][j] == '*') goal = make_pair(i, j);  
  17.       }  
  18.     }  
  19.   
  20.     fill(&path[0][0], &path[H][0], make_pair(-1, -1));  
  21.   
  22.     bool vis[H][W];  
  23.     fill(&vis[0][0], &vis[H][0], false);  
  24.     vis[start.first][start.second] = true;  
  25.   
  26.     const int di[] = {0, 0, -1, +1};  
  27.     const int dj[] = {-1, +1, 0, 0};  
  28.   
  29.     queue< pair<intint> > q;  
  30.     for (q.push(start); q.size() && !vis[goal.first][goal.second]; q.pop()) {  
  31.       pair<intint> curr = q.front();  
  32.       for (int d = 0; d < 4; ++d) {  
  33.         int ni = curr.first + di[d];  
  34.         int nj = curr.second + dj[d];  
  35.         if (ni < 0 || nj < 0) continue;  
  36.         if (h <= ni || w <= nj) continue;  
  37.         if (vis[ni][nj]) continue;  
  38.         if (maze[ni][nj] == 'X'continue;  
  39.         vis[ni][nj] = true;  
  40.         path[ni][nj] = curr;  
  41.         q.push(make_pair(ni, nj));  
  42.       }  
  43.     }  
  44.   
  45.     int ret = 0;  
  46.     pair<intint> p = goal;  
  47.     while (true) {  
  48.       if (p != goal) {  
  49.         ret += (bool)(count(&path[0][0], &path[H][0], p) - 1);  
  50.       }  
  51.       if (p == start) break;  
  52.       p = path[p.first][p.second];  
  53.     }  
  54.   
  55.     return ret;  
  56.   }  
  57. };