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 <stdlib.h>
#include <queue>
#include <cstring>
#define MAX_NUM 1010
using namespace std;
int H, W, N;
bool flag[MAX_NUM][MAX_NUM] = {false};

class Node
{
public:
	Node();
	Node(int x, int y, int step);
	~Node();
	int x;
	int y;
	int step;
};

Node::Node()
{
}

Node::Node(int x, int y, int step) {
	this->x = x;
	this->y = y;
	this->step = step;
}

Node::~Node()
{
}
int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
int BFS(char map[][MAX_NUM], int sx, int sy, int ex, int ey) {
	queue<Node> que;
	Node node(sx, sy, 0);
	que.push(node);
	flag[sx][sy] = true;
	while (!que.empty())
	{
		Node cur = que.front();
		que.pop();
		if (cur.x == ex && cur.y == ey)
		{
			return cur.step;
		}
		else
		{
			for (int i = 0; i < 4; i++)
			{
				int k = cur.x + dir[i][0];
				int v = cur.y + dir[i][1];
				if (k>=0&&k<H&&v>=0&&v<W&&map[k][v]!='X'&&!flag[k][v])
				{
					Node temp(k, v, cur.step + 1);
					que.push(temp);
					flag[k][v] = true;
				}
			}
		}
	}
	return -1;

}

int main()
{
	int sx, sy, arr[10][2];
	char map[MAX_NUM][MAX_NUM];
	while (cin >> H >> W >> N && H && W)
	{
		for (int i = 0; i < H; i++)
		{
			for (int j = 0; j < W; j++)
			{
				cin >> map[i][j];
				if (map[i][j] == 'S')
				{
					map[i][j] = '.';
					sx = i;
					sy = j;
				}
				if (isdigit(map[i][j]))
				{
					int index = map[i][j] - '0';
					arr[index][0] = i;
					arr[index][1] = j;
				}
			}
		}
		arr[0][0] = sx;
		arr[0][1] = sy;
		int res = 0;
		for (int i = 0; i+1 <= N; i++)
		{
			memset(flag, false, sizeof(flag));
			res += BFS(map, arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]);
		}
		cout << res << endl;
	}
	return 0;
}

C++: #include<iostream>
#include<queue>
using namespace std;
struct Data{
    int x;
    int y;
    int t;
};
bool vis[1005][1005];
const int dx[] = {1,0,-1,0},dy[] = {0,1,0,-1};
int main(){
    int h,w,n;
    cin>>h>>w>>n;
    string fi[1020];
    Data init;
    for(int i = 0;i < h;i++){
        cin>>fi[i];
        for(int j = 0;j < w;j++){
            if(fi[i][j] == 'S'){
                init.x = j;
                init.y = i;
            }
        }
    }
    init.t = 0;

    queue<Data> Q;
    Q.push(init);
    int now = 1;
    while(!Q.empty()){
        Data D = Q.front();
        Q.pop();
        D.t++;
        vis[D.y][D.x] = true;
        if(fi[D.y][D.x] == now + '0'){
            now++;
            for(int i = 0;i < h;i++){
                for(int j = 0;j < w;j++){
                    vis[i][j] = false;
                }
            }
            Q = queue<Data>();
            Q.push(D);
        }
        if(now == n+1){
            cout<<D.t-1<<endl;
            return 0;
        }
        for(int i = 0;i < 4;i++){
            int x = D.x + dx[i];
            int y = D.y + dy[i];
            if(0 <= x&&x < w&&0 <= y&& y < h){
                if(fi[y][x] == 'X')continue;
                if(vis[y][x])continue;
                Data E = D;
                E.x = x, E.y = y;
                Q.push(E);
            }
        }
    }
}

C++: #include <iostream>
#include <queue>
#include <vector>
#define MAX 1000

using namespace std;

const int INF = 1000000;

typedef pair<int,int> P;

int n,m;
char cheese[MAX+1][MAX+1];
 
int bfs(int sy,int sx,int gy,int gx){
    
  int dx[4]={1,0,-1,0};
  int dy[4]={0,1,0,-1};
  int d[MAX][MAX];
  queue<P> q;
     
    for( int i = 0 ; i < n ; i++ )
        for( int j = 0 ; j < m ; j++ )
            d[i][j] = INF;
     
    q.push( P(sy , sx) );
    d[sy][sx] = 0;
     
    while( q.size() ){
        P p = q.front(); 
	q.pop();

        if(p.first == gy && p.second == gx) break;
	
        for(int i = 0 ; i < 4 ; i++){
	  int x = p.first + dx[i];
	  int y = p.second + dy[i];
          
	  if( 0 <= x && x < n &&
	      0 <= y && y < m &&
	      d[x][y] == INF &&
	      mp[nx][ny]!='X'){
	    q.push( P(nx , ny) );
	    d[x][y] = d[p.first][p.second] + 1;
	  }
        }
    }
    
    return d[gy][gx];
}

int main(void){

    int n;
 
    cin >> n >> m >> num;
    vector<P> v(num + 1);
     
    for( int i = 0 ; i < n ; i++ ){
        for( int j = 0 ; j < m ; j++ ){
            cin >> cheese[i][j];
            if( cheese[i][j]=='S'){
                v[0].first = i;
                v[0].second = j;
            }
            if('1' <= cheese[i][j] && cheese[i][j] <= '9'){
                v[mp[i][j]-'0'].first = i;
                v[mp[i][j]-'0'].second = j;
            }
        }
    }
     
    int sum = 0;
    for(int i = 1 ; i < num+1 ; i++){
        sum += bfs(v[i-1].first,v[i-1].second,v[i].first,v[i].second);
    }
    cout << sum << endl;
     
    retur

C++: #include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <string.h>
#include <set>
#include <queue>
#include <cmath>
#include <algorithm>

using namespace std;

struct node
{
	int x;
	int y;
	int dist;

	node(int x , int y , int dist)
	{
		this -> x = x;
		this -> y = y;
		this -> dist = dist;
	}
};

bool vis[1010][1010];
char input[1010][1010];
int dx[4] = {- 1 , 0 , 1 , 0};
int dy[4] = {0 , 1 , 0 , - 1};
queue<node> q;
vector<node> pre;

bool inArea(int x , int y , int n , int m)
{
	return x >= 0 && x < n && y >= 0 && y < m;
}

int solve(int sx , int sy , int h , int w , int n)
{
	while (!q.empty())
		q.pop();
	pre.clear();

	int value = 1;
	q.push(node(sx , sy , 0));
	vis[sx][sy] = true;

	while (!q.empty())
	{
		node no = q.front();
		q.pop();
		pre.push_back(node(no.x , no.y , no.dist));

		if (input[no.x][no.y] >= '0' && input[no.x][no.y] <= '9' && ((input[no.x][no.y] - '0') == value))
		{
			value ++;
			if (value == n + 1)
				return no.dist;

			while (!q.empty())
			{
				node temp = q.front();
				q.pop();
				vis[temp.x][temp.y] = false;
			}

			for (int i = 0;i < pre.size() - 1;i ++)
				vis[pre[i].x][pre[i].y] = false;
			pre.clear();
			pre.push_back(node(no.x , no.y , no.dist));
		}
		for (int i = 0;i < 4;i ++)
		{
			int tx = no.x + dx[i];
			int ty = no.y + dy[i];
			if (inArea(tx , ty , h , w) && !vis[tx][ty] && input[tx][ty] != 'X')
			{
				vis[tx][ty] = true;
				q.push(node(tx , ty , no.dist + 1));
			}
		}
	}
	return - 1;
}

int main()
{
	int i , j , h , w , n;
	while (scanf("%d%d%d" , &h , &w , &n) != EOF)
	{
		for (i = 0;i < h;i ++)
			for (j = 0;j < w;j ++)
				vis[i][j] = false;

		int sx , sy;
		for (i = 0;i < h;i ++)
		{
			scanf("%s" , input[i]);
			for (j = 0;j < w;j ++)
			{
				if (input[i][j] == 'S')
				{
					sx = i;
					sy = j;
				}
			}
		}
		// ???S????§????
		printf("%d\n" , solve(sx , sy , h , w , n));
	}
	return 0;
}