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;

typedef pair<int, int> Point;
int h, w, n;
string grid[1001];

int bfs(int sx, int sy, int gx, int gy){
    cout<<"(sx, sy) = "<<"("<<sx<<","<<sy<<")"<<endl;
    bool visited[1001][1001] = {false};
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};

    visited[sy][sx] = true;
    cout<<"(gx, gy) = "<<"("<<gx<<","<<gy<<")"<<endl;

    queue<pair<Point, int> > que;
    pair<Point, int> state;
    que.push(make_pair(Point(sx, sy), 0));
    while (1){
        state = que.front();
        que.pop();

        if (state.first.first == gx && state.first.second == gy){
            return state.second;
        }

        for (int i = 0; i < 4; i++){
            int nx = state.first.first + dx[i];
            int ny = state.first.second + dy[i];
            if (0 <= nx && nx < w && 0 <= ny && ny < h 
                && grid[ny][nx] != 'X' && visited[ny][nx] == false){
                visited[ny][nx] = true;
                que.push(make_pair(Point(nx, ny), state.second + 1));
            }
        }
    }
}

int main(int argc, char const *argv[]){
    int sx, sy, gx, gy;
    int ans = 0;
    cin>>h>>w>>n;
    for (int i = 0; i < h; i++){
        cin>>grid[i];
    }

    for (int i = 0; i < h; i++){
        for (int j = 0; j < w; j++){
            if (grid[i][j] == 'S'){
                sx = j; sy = i;
            }
            if (grid[i][j] == '1'){
                gx = j; gy = i;
            }
        }
    }

    for (int size = 2; size-1 <= n; size++){
        ans += bfs(sx, sy, gx, gy);

        sx = gx; sy = gy;
        for (int i = 0; i < h; i++){
            for (int j = 0; j < w; j++){
                if (grid[i][j] - '0' == size){
                    gx = j; gy = i;
                }
            }
        }
    }

    cout<<ans<<endl;

    return 0;
}

C++: #include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

const int hw_max = 1000 + 5;
char graph[hw_max][hw_max];
int sign[hw_max][hw_max];
int h, w, n, ans;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
struct node
{
    int x;
    int y;
    int time;
} start;

void BFS(node op, char ed)
{
    queue <node> process;
    process.push(op);
    sign[op.x][op.y] = 1;
    while(!process.empty())
    {
        node now = process.front();
        process.pop();
        for(int i = 0; i < 4; i ++)
        {
            node next = now;
            next.x += dx[i];
            next.y += dy[i];
            next.time ++;
            if(next.x >= 0 && next.x < h && next.y >= 0 && next.y < w && graph[next.x][next.y] != 'X' && !sign[next.x][next.y])
            {
                if(graph[next.x][next.y] == ed)
                {
                    ans += next.time;
                    next.time = 0;
                    start = next;
                        return;
                }
                else
                {
                    process.push(next);
                    sign[next.x][next.y] = 1;
                }
            }
        }
    }
}

int main()
{
    while(~scanf("%d %d %d", & h, & w, & n))
    {
        getchar();
        for(int i = 0; i < h; i ++)
        {
            for(int j = 0; j < w; j ++)
            {
                   scanf("%c", & graph[i][j]);
                   if(graph[i][j] == 'S')
                   {
                    start.x = i;
                    start.y = j;
                    start.time = 0;
                   }
            }
            getchar();
        }
        ans = 0;
        for(int i = 1; i <= n; i ++)
        {
            memset(sign, 0, sizeof(sign));
            BFS(start, '0' + i);
        }
        printf("%d\n", ans);
    }
    return 0;
}

C++: //#include "stdafx.h"
#include <iostream>
#include <queue>
#include <cstring>
#define INF 1000000000
using namespace std;

int row, col, n;

typedef struct point {
	int x, y;
};

char map[1000][1000];
int d[1000][1000];
int direct[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };

int BFS(int &startX, int &startY, char target) {
	for (int i = 0; i < row; i++)
		for (int j = 0; j < col; j++)
			d[i][j] = INF;

	queue<point> q;
	point p;
	p.x = startX;
	p.y = startY;
	d[startX][startY] = 0;
	q.push(p);
	while (!q.empty()) {
		int nowX = q.front().x,nowY = q.front().y;
		q.pop();

		if (map[nowX][nowY] == target) {
			startX = nowX;
			startY = nowY;
			return d[nowX][nowY];
		}

		int nextX, nextY;
		for (int i = 0; i < 4; i++) {
			nextX = nowX + direct[i][0];
			nextY = nowY + direct[i][1];

			if (nextX >= 0 && nextY >= 0 && nextX < row && nextY < col && 
					map[nextX][nextY] != 'X' && d[nextX][nextY] == INF) {
				d[nextX][nextY] = d[nowX][nowY] + 1;
				p.x = nextX;
				p.y = nextY;
				q.push(p);
			}
		}
	}
	return -1;
}

int main() {
	int startX, startY, sum = 0;

	cin >> row >> col >> n;
	for (int i = 0; i < row; i++) {
		cin >> map[i];
		for (int j = 0; j < col; j++) {
			if (map[i][j] == 'S') {
				startX = i;
				startY = j;
			}
		}
	}

	for (int i = 0; i < n; i++) {
		int dis = BFS(startX, startY, i + '1');

		if (dis == -1)cout << "error" << endl;
		else sum += dis;
	}
	cout << sum << endl;
}

C++: #include <iostream>
#include <map>
#include <queue>
#define F first
#define S second
#define INF 1<<21
using namespace std;
typedef pair<int,int>P;
int bfs();
int d[1111][1111];
int sx,sy;
int h,w,n;
char num;
char s[1111][1111];
int main(){
  int ans=0;
  cin >> h >> w >> n;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      cin >> s[i][j];
      if(s[i][j]=='S'){
	sx=j,sy=i;
      }
    }
  }
  for(num='1';num<'1'+n;num++){
    ans+=bfs();
  }
  cout << ans << endl;
}

int bfs(){
  queue <P>q;
  int dx[4]={0,1,0,-1};
  int dy[4]={1,0,-1,0};
  int nx,ny;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      d[i][j]=INF;
    }
  }
  
  q.push(P(sy,sx));
  d[sy][sx]=0;
  while(q.size()){
    P p=q.front();
    q.pop();
    if(s[p.F][p.S]==num){
      sy=p.F;
      sx=p.S;
      return d[p.F][p.S];
    }    
    for(int i=0;i<4;i++){
      nx=p.S+dx[i],ny=p.F+dy[i];
      if(s[ny][nx]!='X' && nx<w && nx>=0 && ny<h && ny>=0 && d[ny][nx]==INF){
	q.push(P(ny,nx));
	d[ny][nx]=d[p.F][p.S]+1;
      }
    }
  }
}