Go: ///
// File:  0558.go
// Author: ymiyamoto
//
// Created on Sun Mar  4 20:58:45 2018
//
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type pos struct {
	x, y int
}

var H, W, N int
var graph [][]string

func wfs(p pos, index int) (int, pos) {
	var q []pos
	dists := make([][]int, H)
	for i := range dists {
		dists[i] = make([]int, W)
	}

	q = append(q, p)
	for len(q) > 0 {
		p := q[0]
		dist := dists[p.x][p.y]
		q = q[1:]

		for _, d := range []pos{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} {
			x := p.x + d.x
			y := p.y + d.y
			if 0 <= x && x < H && 0 <= y && y < W && graph[x][y] != "X" && dists[x][y] == 0 {
				dists[x][y] = dist + 1
				q = append(q, pos{x, y})
			}
		}
	}

	for i := range graph {
		for j := range graph[i] {
			if graph[i][j] == strconv.Itoa(index) {
				return dists[i][j], pos{i, j}
			}
		}
	}

	panic("not found")
}

func main() {
	fmt.Scan(&H, &W, &N)

	var start pos

	graph = make([][]string, H)
	for i := range graph {
		var s string
		fmt.Scan(&s)
		graph[i] = strings.Split(s, "")
		for j := range graph[i] {
			if graph[i][j] == "S" {
				start.x = i
				start.y = j
			}
		}
	}

	count := 0
	for i := 1; i <= N; i++ {
		c, s := wfs(start, i)
		start = s
		count += c
	}

	fmt.Println(count)
}

C++: #include <iostream>
#include <queue>

using namespace std;

char mp[1005][1005];
int vis[1005][1005];
int w, h, n;

int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int ans = 0, sx, sy;
int blood = 1;

struct Node{
	int x,y;
	Node(int _x, int _y){
		x = _x, y = _y;
	}
}; 
typedef struct Node Node; 

queue<Node> que;

void bfs(char t){
//	cout<<"sx = "<<sx<<", sy = "<<sy<<endl;
	que.push(Node(sx, sy));
	ans = 0;
	bool flag = true;
	while(!que.empty()){
//		cout<<"ans = "<<ans<<"n = "<<n<<endl;
		int size = que.size();
		for(int i = 0; i < size; i++){
			Node node = que.front();
			que.pop();
			int x = node.x, y = node.y;
//			cout<<"x = "<<x<<", y = "<<y<<endl;
			for(int i = 0; i < 4; i++){
				int tx = x + dirs[i][0], ty = y + dirs[i][1];
				if(tx >= 0 && tx < h && ty >= 0 && ty < w && vis[tx][ty] == 0 && mp[tx][ty] == t){
					sx = tx, sy = ty;
					ans++;
					flag = false;
					return;
				}else if(tx >= 0 && tx < h && ty >= 0 && ty < w && vis[tx][ty] == 0 &&  mp[tx][ty] != 'X'){
//					cout<<"tx = "<<tx<<", ty = "<<ty<<endl;
					que.push(Node(tx, ty));
					vis[tx][ty] = 1;
				}
			} 
		}
		ans++;
	}
	if(flag) ans = 0;
}

int main(){
	cin>>h>>w>>n;
	for(int i = 0; i < h; i++){
		scanf(" %s", mp[i]);
	}
	for(int i = 0; i < h; i++){
		for(int j = 0; j < w; j++){
			if(mp[i][j] == 'S'){
				sx = i, sy = j;
			}
		}
	}
	int res = 0;
	for(int i = 1; i <= n; i++){
		bfs(i + '0');
		for(int m = 0; m < h; m++)
			for(int k = 0; k < w; k++)
				vis[m][k] = 0;
		while(!que.empty())que.pop();
		res += ans;
	}
	cout<<res<<endl;
	return 0;
}

/**
331
S..
...
..1
*/

C++: #include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int n,m,s,ne[4][2]={0,1,0,-1,1,0,-1,0};
char mmp[1003][1003];
bool vis[1003][1003];
class qaq
{
public:
    int x,y,step,strength;
    qaq():x(0),y(0),step(0){};
};
queue<qaq> que;
int bfs(int x,int y)
{
    qaq q,p;
    q.x=x;
    q.y=y;
    q.step=0;
    q.strength=1;
    vis[x][y]=true;
    que.push(q);
    while(!que.empty()){
        q=que.front();
        que.pop();
        if(q.strength==s+1)
            return q.step;
        for(int i=0;i<4;i++){
            p.x=q.x+ne[i][0];
            p.y=q.y+ne[i][1];
            if(p.x<0||p.x>=n||p.y<0||p.y>=m||vis[p.x][p.y])
                continue;
            if(mmp[p.x][p.y]=='.'){
                p.step=q.step+1;
                p.strength=q.strength;
                vis[p.x][p.y]=true;
                que.push(p);
            }
            else if(q.strength==mmp[p.x][p.y]-'0'){
            	mmp[p.x][p.y]='.';
                p.step=q.step+1;
                p.strength=q.strength+1;
                memset(vis,0,sizeof(vis));
                while(!que.empty()) que.pop();
                que.push(p);
                break;
            }
            else if(mmp[p.x][p.y]!='X'){
            	p.step=q.step+1;
                p.strength=q.strength;
                vis[p.x][p.y]=true;
                que.push(p);
			}
        }
    }
}
int main()
{
    int startx,starty;
    while(scanf("%d %d %d",&n,&m,&s)!=EOF){
        while(!que.empty()) que.pop();
        memset(vis,0,sizeof(vis));
        for(int i=0;i<n;i++){
            scanf("%s",&mmp[i]);
            for(int j=0;j<m;j++){
                if(mmp[i][j]=='S'){
                    startx=i;
                    starty=j;
                    mmp[i][j]='.';
                }
            }
        }
        int ans=bfs(startx,starty);
        printf("%d\n",ans);
    }
    return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int h, w, n, s;
char g[1001][1001];
bool v[1001][1001];
int id[8] = {0, -1, 0, 1, -1, 0, 1, 0};
int main() {
    scanf("%d %d %d", &h, &w, &n);
    for (int i = 0; i < h; ++i) {
        getchar();
        for (int j = 0; j < w; ++j) {
            while (~scanf("%c", &g[i][j]) && g[i][j] == ' ');
            //printf("%c",g[i][j]);
            if (g[i][j] == 'S') s = i * w + j;
        }
    }
    int ans = 0;
    char c = '0';
    while (c != n + '0') {
        c += 1;
        queue<pair<int, int> > q;
        memset(v, 0, sizeof v);
        v[s / w][s % w] = true;
        q.push({s, 0});
        while (!q.empty()) {
            int i = q.front().first / w, j = q.front().first % w, step = q.front().second;
            //printf("123%d\n%c\n", step, g[i][j]);
            if (g[i][j] == c) {
                s = i * w + j;
                ans += step;
                printf("%d %d %d\n", i, j, ans);
                break;
            }
            q.pop();
            for (int k = 0; k < 8; k += 2) {
                int ni = i + id[k], nj = j + id[k + 1];
                if (ni >= 0 && ni < h && nj >= 0 && nj < w && !v[ni][nj] && (g[ni][nj] == '.' || g[ni][nj] <= c)) {
                    v[ni][nj] = true;
                    q.push({ni * w + nj, step + 1});
                }
            }
        }
    }
    printf("%d\n", ans);
    return 0;
}

C++: #include <bits/stdc++.h>
#define int long long
#define double long double
#define INF 1e18
using namespace std;
queue< pair<int,int> > q;
int original[1010][1010];
int grid[1010][1010];
pair<int,int> cheese[10];
int H, W, N, ans = 0;

void resetGrid(pair<int,int> p) {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      grid[j][i] = original[j][i];
      if (p.first == j && p.second == i) grid[j][i] = 0;
    }
  }
}

void bfs() {
  int mX[] = { 1, 0, -1, 0 };
  int mY[] = { 0, 1, 0, -1 };
  for (int i = 0; i < N; i++) {
    resetGrid(cheese[i]);
    q.push(cheese[i]);
    while (q.size() > 0) {
      pair<int,int> p = q.front();
      q.pop();
      int x = p.first, y = p.second;
      for (int j = 0; j < 4; j++) {
        int _x =x+mX[j], _y =y+mY[j];
        if (_x < 0 || _y < 0 || _x >= W || _y >= H || grid[_x][_y] != INF) continue;
        grid[_x][_y] = grid[x][y]+1;
        q.push(make_pair(_x, _y));
      }
    }
    ans += grid[cheese[i+1].first][cheese[i+1].second];
  }
}

signed main() {
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      char c; cin >> c;
      if (c == 'S') {
        original[j][i] = INF;
        cheese[0] = make_pair(j, i);
      } else if (c == 'X') {
        original[j][i] = -1;
      } else if (c == '.') {
        original[j][i] = INF;
      } else {
        original[j][i] = INF;
        cheese[(c-'0')] = make_pair(j, i);
      }
    }
  }

  bfs();

  cout << ans << endl;
}