Problem p00481 (C++) — buggy submission, verdict: Time Limit Exceeded

#include <algorithm>
#include <iostream>
#include <queue>
const int INF = 100000000;
using namespace std;
typedef pair<int, int> P;
char a[1005][1005];
int N, M;
int sx, sy;
int gx, gy;
int d[1005][1005];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int bfs() {
  queue<P> que;
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++)
      d[i][j] = INF;
  que.push(P(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    P p = que.front();
    que.pop();
    if (p.first == gx && p.second == gy)
      break;
    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i];
      int ny = p.second + dy[i];
      if (nx >= 0 && nx < N && ny >= 0 && ny < M && a[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  return d[gx][gy];
}
int main(void) {
  while (cin >> N >> M) {
    int n, sum = 0;
    cin >> n;
    for (int i = 0; i < N; i++)
      for (int j = 0; j < M; j++)
        cin >> a[i][j];
    for (int j = 0; j < N; j++)
      for (int k = 0; k < M; k++)
        if (a[j][k] == 'S') {
          sx = j;
          sy = k;
        }
    for (int j = 0; j < N; j++)
      for (int k = 0; k < M; k++)
        if (a[j][k] == '1') {
          gx = j;
          gy = k;
        }
    sum += bfs();
    for (int i = 0; i < n - 1; i++) {
      for (int j = 0; j < N; j++)
        for (int k = 0; k < M; k++) {
          if (a[j][k] == (char)(i + 49)) {
            sx = j;
            sy = k;
          }
          if (a[j][k] == (char)(i + 50)) {
            gx = j;
            gy = k;
          }
        }
      sum += bfs();
    }
    cout << sum << endl;
  }
}

Error: TLE

Fixed submission:

// TEMPLATE BEGIN
// #define ONLINE_JUDGE
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
// #include <ctime>
#include <algorithm>
#include <bitset>
#include <complex>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <vector>
using namespace std;

#define FOR(i, a, b) for (int(i) = (a); (i) <= (b); ++(i))
#define ROF(i, a, b) for (int(i) = (a); (i) >= (b); --(i))
#define FOREDGE(i, u, head, next)                                              \\
  for (int(i) = (head[(u)]); (i); (i) = (next[(i)]))
#define FORSTL(it, A)                                                          \\
  for (__typeof((A).begin()) it = (A).begin(); it != (A).end(); ++it)
#define CLR(a, b) memset((a), (b), sizeof(a))
#define CPY(a, b) memcpy((a), (b), sizeof(a))
#define DEBUG cerr << "debug" << endl
#define STAR cerr << "**********" << endl

#define RT return
#define BK break
#define CT continue
#define ALL(x) (x).begin(), (x).end()
#define HEAP priority_queue
#define st first
#define nd second
#define pf push_front
#define pb push_back
#define ppf pop_front
#define ppb pop_back
#define mp make_pair
#define re real()
#define im imag()

#define LIST0(A, n)                                                            \\
  {                                                                            \\
    FOR(i, 0, n - 1) printf("%d ", A[i]);                                      \\
    printf("\\n");                                                              \\
  }

#define LIST1(A, n)                                                            \\
  {                                                                            \\
    FOR(i, 1, n) printf("%d ", A[i]);                                          \\
    printf("\\n");                                                              \\
  }

#define SHOW0(A, n, m)                                                         \\
  {                                                                            \\
    FOR(i, 0, n - 1) {                                                         \\
      FOR(j, 0, m - 1)                                                         \\
      printf("%d ", A[i][j]);                                                  \\
      printf("\\n");                                                            \\
    }                                                                          \\
  }

#define SHOW1(A, n, m)                                                         \\
  {                                                                            \\
    FOR(i, 1, n) {                                                             \\
      FOR(j, 1, m)                                                             \\
      printf("%d ", A[i][j]);                                                  \\
      printf("\\n");                                                            \\
    }                                                                          \\
  }

typedef long long LL;
typedef double DB;
typedef long double LDB;
typedef unsigned int UINT;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef vector<DB> VB;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef map<int, int> MII;
typedef map<LL, LL> MLL;
typedef map<int, string> MIS;
typedef map<string, int> MSI;

const int INF(0x3f3f3f3f);
const LL LINF(0x3f3f3f3f3f3f3f3fLL);
const DB DINF(1e20);
const DB EPS(1e-12); // adjustable
const DB PI(acos(-1.0));

inline DB cot(DB x) { RT 1.0 / tan(x); }
inline DB sec(DB x) { RT 1.0 / cos(x); }
inline DB csc(DB x) { RT 1.0 / sin(x); }

template <class T> inline T max(T a, T b, T c) { RT max(max(a, b), c); }
template <class T> inline T max(T a, T b, T c, T d) {
  RT max(max(a, b), max(c, d));
}
template <class T> inline T min(T a, T b, T c) { RT min(min(a, b), c); }
template <class T> inline T min(T a, T b, T c, T d) {
  RT min(min(a, b), min(c, d));
}

template <class T> inline void Scan(T &x) { // int, LL
  char c;
  for (c = getchar(); c <= ' '; c = getchar())
    ;
  bool ngt(c == '-');
  if (ngt)
    c = getchar();
  for (x = 0; c > ' '; c = getchar())
    x = (x << 3) + (x << 1) + c - '0';
  if (ngt)
    x = -x;
}
template <class T> inline void Scan(T &x, T &y) { Scan(x), Scan(y); }
template <class T> inline void Scan(T &x, T &y, T &z) {
  Scan(x), Scan(y), Scan(z);
}
// TEMPLATE END

const int N = 1010;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};

int h, w, n, d[N][N];
char G[N][N];
PII pos[10];
queue<PII> Q;

int BFS(PII s, PII t) {
  CLR(d, -1);
  Q.push(s);
  d[s.st][s.nd] = 0;
  while (!Q.empty()) {
    PII tmp = Q.front();
    Q.pop();
    FOR(i, 0, 3) {
      int nx = tmp.st + dx[i], ny = tmp.nd + dy[i];
      if (1 <= nx && nx <= h && 1 <= ny && ny <= w && G[nx][ny] != 'X' &&
          d[nx][ny] == -1) {
        Q.push(mp(nx, ny));
        d[nx][ny] = d[tmp.st][tmp.nd] + 1;
        if (mp(nx, ny) == t)
          BK;
      }
    }
  }
  RT d[t.st][t.nd];
}

void Main() {
  Scan(h, w, n);
  FOR(i, 1, h) {
    scanf("%s", G[i] + 1);
    FOR(j, 1, w) {
      if (isdigit(G[i][j]))
        pos[G[i][j] - '0'] = mp(i, j);
      else if (G[i][j] == 'S')
        pos[0] = mp(i, j);
    }
  }

  int ans = 0;
  FOR(i, 1, n) ans += BFS(pos[i - 1], pos[i]);
  printf("%d\\n", ans);
}

int main() {
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  freopen("output.txt", "w", stdout);
#endif
  Main();
  RT 0;
}
// imagasaikou!