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<deque>

using namespace std;

int H, W, N;
char mapT[1000][1000];
int vis[1000][1000];
int temp_x = 0, temp_y;
char temp;
int final_min_route = 0;
int dir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };

struct location {
	int x, y, route;
};

location findSmallRouteBFS(int x, int y, char factory) {
	memset(vis, 0, sizeof(vis));
	deque<location> que;
	location temp = { x,y,0 };
	que.push_back(temp);
	vis[x][y] = 1;
	while (!que.empty()) {
		location st = que.front();
		que.pop_front();
		if (mapT[st.x][st.y] == factory) {
			return st;
		}
		for (int i = 0; i < 4; ++i) {
			int t_x = st.x + dir[i][0];
			int t_y = st.y + dir[i][1];
			if (t_x < 0 || t_x >= H || t_y < 0 || t_y >= W || mapT[t_x][t_y] == 'X') {
				continue;
			}
			location temp = { t_x,t_y,st.route + 1 };
			if (!vis[t_x][t_y]) {
				vis[t_x][t_y] = 1;
				que.push_back(temp);
			}
		}
	}

}

int main() {
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; ++j) {
			cin >> temp;
			mapT[i][j] = temp;
			if (temp == 'S') {
				mapT[i][j] = '0';
				temp_x = i;
				temp_y = j;
			}
		}
	}

	for (int factory = 1; factory != N + 1; ++factory) {

		location lo = findSmallRouteBFS(temp_x, temp_y, mapT[temp_x][temp_y] + 1);
		temp_x = lo.x;
		temp_y = lo.y;
		final_min_route += lo.route;
	}

	cout << final_min_route << endl;
	//system("pause");
	return 0;
}

C++: #include<cmath>
#include<cctype>
#include<cstdlib>
#include<cstdio>
#include<climits>
#include<iostream>
#include<algorithm>
#include<vector>
#include<deque>
#include<string>
#include<queue>
#include<map>
#include<set>
#include<utility>
#include<queue>

using namespace std;
#define is ==
int W,H,N;
const int MAX = 1000;
char f[MAX][MAX];
int d[MAX][MAX];
int dx[] = {0,0,-1,1};
int dy[] = {-1,1,0,0};
struct P
{
  int x,y;
};
inline bool check(P p){
  return p.x < 0 or p.x >= W or p.y < 0 or p.y >= H;
}
int bfs(P s,int goal){
  if(goal > N+'0')return 0;
  fill(*d,*(d+MAX),-1);
  queue<P> que;
  que.push(s);
  d[s.x][s.y] = 0;
  while(!que.empty()){
    P cur = que.front();que.pop();

    if(f[cur.x][cur.y] is goal)return d[cur.x][cur.y] + bfs(cur,goal+1);

    for (int i = 0; i < 4; ++i){
      P np = {cur.x+dx[i],cur.y+dy[i]};
      if(check(np))continue;
      if(f[np.x][np.y] is 'X')continue;
      if(d[np.x][np.y] > -1)continue;//visited
      d[np.x][np.y] = d[cur.x][cur.y] + 1;
      que.push(np);
    }
  }
  cout << "no goal!" << endl;
  return 0;//error
}

int main(){
  ios::sync_with_stdio(false);
  while(cin >> H >> W >> N){
    P s;
    for (int j = 0; j < H; ++j){
      for (int i = 0; i < W; ++i){
	cin >> f[i][j];
	if(f[i][j] == 'S')s.x = i,s.y = j;
      }
    }
    cout << bfs(s,'1') << endl;
  }
  return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
using namespace std;

int H,W,N,sx,sy,ans;
int tx,ty,pre_lastx,pre_lasty,tmpx,tmpy;
char g[1005][1005];
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};

int bfs(int n){
    queue<pair<int,int> > q;
    bool flag[1005][1005]={0};
    tx=sx,ty=sy,pre_lastx=sx,pre_lasty=sy,tmpx=sx,tmpy=sy;
    q.push(pair<int,int>(tx,ty));
    int t=0;
    flag[tx][ty]=true;
    while(!q.empty()){
        pair<int,int> p=q.front();q.pop();

        if(g[p.first][p.second]==char('0'+n)){
            sx=p.first;sy=p.second;
            break;
        }
        for(int i=0;i<4;i++){
            tx=p.first+dx[i];ty=p.second+dy[i];
            if(tx>=0&&tx<H&&ty>=0&&ty<W&&g[tx][ty]!='X'&&!flag[tx][ty]){
                q.push(pair<int,int>(tx,ty));
                flag[tx][ty]=true;
                tmpx=tx;tmpy=ty;
            }
        }
        if(p.first==pre_lastx&&p.second==pre_lasty){
            pre_lastx=tmpx;pre_lasty=tmpy;
            t++;
        }
    }

    return t;
}

int main(){
    cin>>H>>W>>N;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin>>g[i][j];
            if(g[i][j]=='S'){
                sx=i;sy=j;
            }
        }
    }

    ans=0;
    for(int i=1;i<=N;i++){
        ans+=bfs(i);
    }
    cout<<ans<<endl;

    return 0;
}

C++: #include <iostream>
#include <algorithm>
#include <queue>
#include <cstdio>
using namespace std;

int h,w;
int sx,sy,gx,gy;
char rec[1000][1000];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int used[1001][1001];

bool check(int x, int y){
  return x >= 0 && y >= 0 && x < w && y < h && rec[y][x] != 'X' 
    && used[y][x] == 0;
}

int bfs(int p){
  queue<pair<int,int> > que;
  que.push(make_pair(sy,sx));
  for(int i=0; i<1001; i++)
    for(int j=0; j<1001; j++)
      used[i][j] = 0;
  
  while(!que.empty()){
    pair<int,int> pos = que.front();
    for(int i=0; i<4; i++){
      int yy = pos.first + dy[i];
      int xx = pos.second + dx[i];

      if(check(xx,yy)){
	que.push(make_pair(yy,xx));
	used[yy][xx] = used[pos.first][pos.second] + 1;
      }
         
      if(rec[yy][xx] == p + '0'){
	sx = xx;
	sy = yy;
	return used[sy][sx];
      }
    }
    que.pop();
  }
}

int main()
{
  int n;
 
  cin>>h>>w>>n;

  for(int i=0; i<h; i++){
    for(int j=0; j<w; j++){
      cin>>rec[i][j];
      if(rec[i][j] == 'S'){
	sy = i;
	sx = j;
      }
    }
  }

  int res = 0;

  for(int i=1; i<=n; i++) {
    res += bfs(i);
  }
  cout<<res<<endl;

  return 0;
  
}

C++: #include <cstdio>
#include <utility>
#include <queue>

using namespace std;

typedef pair<int, int> P;
typedef pair<P, P> RAT;

char map[1005][1005];
int H,W,N;
int sx,sy;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};

int main()
{
	queue<RAT> que;
	int tx,ty;
	scanf("%d %d %d",&H,&W,&N);
	for(int i=0;i<H;i++)
	{
		scanf("%s",map[i]);
		for(int j=0;j<W;j++)
			if(map[i][j] == 'S')
			{
				sx = i;
				sy = j;
			}
	}
	
	que.push(RAT(P(sx,sy),P(1,0)));
	for(;;)
	{
		RAT rat = que.front();
		que.pop();
		if(rat.second.first == N+1)
		{
			printf("%d\n",rat.second.second);
			break;
		}
		for(int i=0;i<4;i++)
		{
			tx = rat.first.first + dx[i];
			ty = rat.first.second + dy[i];
			if(tx >= 0 && tx < H && ty >= 0 && ty < W && map[tx][ty] != 'X')
			{
				if(rat.second.first == map[tx][ty]-48)
					que.push(RAT(P(tx,ty),P(rat.second.first+1,rat.second.second+1)));
				else
					que.push(RAT(P(tx,ty),P(rat.second.first,rat.second.second+1)));
			}
		}
	}
	return 0;	
}