1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;

#define INF 99999

const int N = 20;
const int MAX = 100;
int dp[1<<N][N];
char board[MAX][MAX];
int dist[N][N];
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
vector< pair<int, int> > points;
int h, w;

class Orienteering {
  public:
    void main();
};

inline bool isvalid(pair<int, int> pt) {
  return ((0 <= pt.first && pt.first < h) && (0 <= pt.second && pt.second < w) && board[pt.first][pt.second] != '#');
}

void Orienteering::main() {
  int s, g;
  cin >> w >> h;
  if(w > MAX || h > MAX) {
    cout << "-1\n";
    return;
  }
  for(int i = 0; i < h; i++) cin >> board[i];
  for(int i = 0; i < h; i++)
    for(int j = 0; j < w; j++) {
      if(board[i][j] == '@' || board[i][j] == 'S' || board[i][j] == 'G') points.push_back(make_pair(i, j));
      if(board[i][j] == 'S') s = points.size() - 1;
      if(board[i][j] == 'G') g = points.size() - 1;
    }
  if(points.size() > N) {
    cout << "-1\n";
    return;
  }
  int d[MAX][MAX];
  for(int idx = 0; idx < points.size(); idx++) {
    memset(d, -1, sizeof d);
    pair<int, int> u, v;
    queue< pair<int, int> > q;
    q.push(points[idx]);
    d[points[idx].first][points[idx].second] = 0;
    while(!q.empty()) {
      u = q.front(); q.pop();
      for(int i = 0; i < 4; i++) {
        v.first = u.first + dx[i];
        v.second = u.second + dy[i];
        if(!isvalid(v)) continue;
        if(d[v.first][v.second] == -1) {
          d[v.first][v.second] = d[u.first][u.second] + 1;
          q.push(v);
        }
      }
    }
    for(int i = 0; i < points.size(); i++)
      dist[idx][i] = d[points[i].first][points[i].second];
  }
  const int n = points.size();
  for(int mask = 1; mask < (1<<n); mask++) fill(dp[mask], dp[mask] + n, INF);
  dp[1<<s][s] = 0;
  for(int mask = 1; mask < (1<<n); mask++) {
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) if(mask & (1<<j)) 
        dp[mask|(1<<i)][i] = min(dp[mask|(1<<i)][i], dp[mask][j] + dist[j][i]);
    }
  }
  if(dp[(1<<n) - 1][g] >= INF) cout << "-1\n";
  else cout << dp[(1<<n) - 1][g] << "\n";
}

int main(int argc, char* argv[]) {
  Orienteering o;
  o.main();
  return 0;
}