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++: // 111.cpp : 定?控制台?用程序的入口点。
//

#include "stdafx.h"
#include<stdio.h>
#include <queue>
using namespace std;

#define N 1001
int cols,rows,n;
char a[N][N];
bool visited[N][N] = {0};
int minTime;
int direction[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};

struct Point{
	int x;
	int y;
};

bool isInMap(Point p){
	if(p.x < 0 || p.x >= rows)return 0;
	if(p.y < 0 || p.y >= cols)return 0;
	else return 1;
}

int bfs(Point startP,Point endP){
	//printf("strat x = %d y= %d\n",startP.x,startP.y);
	//printf("end x = %d y = %d\n",endP.x,endP.y);
	
	int count = 1;
	queue<Point> point;
	int time =0;
	point.push(startP);
	visited[startP.x][startP.y] = 1;

	while(point.size()){
		int count1 = count;
		//printf("count1 = %d\n",count1);
		count = 0;
		time++;
		for(int i = 0; i < count1; i++)
		{
			//printf("time = %d",time);
			Point cur = point.front();
			
			point.pop();
			for(int j = 0 ; j < 4; j++)
			{
				Point temp;
				temp.x = cur.x + direction[j][0];
				temp.y = cur.y + direction[j][1];
				if(isInMap(temp) && a[temp.x][temp.y] != 'X' && visited[temp.x][temp.y] == 0)
				{
					point.push(temp);
					visited[temp.x][temp.y] = 1;
					count++;
				}
				if(temp.x == endP.x && temp.y == endP.y)return time;
			}
		}
	}


}

int main(){
	Point startP,endP;
	int totalStep = 0;
    scanf("%d%d%d",&rows,&cols,&n);
	getchar();

	for(int i = 0; i < rows; i++)
	{
		for(int j = 0 ; j < cols; j++)
		{
			scanf("%c",&a[i][j]);
			if(a[i][j] == 'S'){a[i][j] = '0';}
		}
		getchar();
	}

	minTime = 100000;
	for(int k = 0; k < n; k++)
	{
		for(int i = 0; i < rows; i++)
			for(int j = 0; j <cols; j++)
			{
				if((int)a[i][j] == (k+48)){startP.x = i;startP.y = j;}
				if((int)a[i][j] == (k+1+48)){endP.x = i;endP.y = j;}
				visited[i][j] = 0;
			}
		totalStep += bfs(startP,endP);
	}
	printf("%d",totalStep);
}

C++: #include<iostream>
#include<string.h>
#include<queue>

using namespace std;

typedef pair<int, int>P;
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
int m, n, N;
char mat[1002][1002];
int d[1002][1002];
int ans;

int bfs(int sx, int sy, int goal){
    memset(d, -1, sizeof(d));
    queue<P>que;
    que.push(P(sx, sy));
    d[sx][sy] = 0;

    while(que.size()){
        P p = que.front();
        que.pop();
        int x = p.first, y = p.second;
        if(mat[x][y] == goal){
            //cout<<x<<" "<<y<<" "<<d[x][y]<<endl;
            return d[x][y];
        }

        for(int i = 0; i < 4; ++i){
            int gx = x + dx[i], gy = y + dy[i];
            if(0 <= gx && gx < m && 0 <= gy && gy < n
               && mat[gx][gy] != 'X' && d[gx][gy] == -1){
                   que.push(P(gx, gy));
                   d[gx][gy] = d[x][y] + 1;
            }
        }
    }
}

void solve(){
    for(int i = 0; i < m; ++i){
        for(int j = 0; j < n; ++j){
            cin>>mat[i][j];
        }
    }

    ans = 0;
    char start = 'S';
    for(int k = 0; k < N; ++k){
        char goal = '1' + k;
        for(int i = 0; i < m; ++i){
            for(int j = 0; j < n; ++j){
                if(mat[i][j] == start){

                    //cout<<bfs(i, j, goal)<<endl;
                    ans += bfs(i, j, goal);
                }
            }
        }
        start = goal;
    }
    cout<<ans<<endl;
}

int main(){
    while(cin>>m>>n>>N && m > 0 && n > 0){
        solve();
    }
    return 0;
}

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

#define MAXN 1024

using namespace std;

struct state{
  int i,j;
  int cost;
  state(int i, int j, int cost):i(i),j(j),cost(cost){}
};

const int di[] = {-1,0,1,0};
const int dj[] = {0,1,0,-1};
const int infty =  1<<28;

int dist[10][10];

bool isinside(int i, int j, int H, int W){
  return 0<=i&&i<H&&0<=j&&j<W;
}

int compute_dist(int n, int H, int W, char M[MAXN][MAXN]){
  int si,sj;
  queue< state > q;
  bool vis[H][W];
  dist[n][n]=0;
  for(int i = 0; i < H; ++i){
    for(int j = 0; j < W; ++j){
      vis[i][j]=false;
      if(M[i][j]-'0' == n){
	si = i;
	sj = j;
      }
    }
  }
  q.push( state(si,sj,0) );
  while(!q.empty()){
    state nst=q.front();q.pop();
    for(int k = 0; k < 4; ++k){
      int ni = nst.i + di[k];
      int nj = nst.j + dj[k];
      if( isinside(ni,nj,H,W) && !vis[ni][nj] && M[ni][nj] !='X' ){
	if( isdigit(M[ni][nj]) ){
	  dist[n][M[ni][nj]-'0'] = nst.cost+1;
	}
	vis[ni][nj]=true;
	q.push( state(ni,nj,nst.cost+1) );
      }
    }
  }
}

int solve(int H, int W, int N, char M[MAXN][MAXN])
{
  int vis[N];
  for(int i = 0; i <= N; ++i){
    compute_dist(i,H,W,M);
    if(i>0)vis[i-1]=i;
  }
  int min_cost = infty;
  do{
    int now=0;
    int now_power = 1;
    int cost=0;
    for(int i = 0; i < N; ++i){
      if( now_power < vis[i] ){
	cost = infty;
	break;
      }else{
	now_power += 1;
	//cout << now << ' ' << vis[i] << ' ' << dist[now][vis[i]] << endl;
	cost += dist[now][vis[i]];
	now = vis[i];
      }
    }
    min_cost = min( min_cost, cost );
  }while(next_permutation(vis,vis+N));
  return min_cost;
}

int main()
{
  int H,W,N;
  while(cin >> H >> W >> N){
    static char M[MAXN][MAXN];
    for(int i = 0; i < H; ++i){
      for(int j = 0; j < W; ++j){
	cin >> M[i][j];
	if(M[i][j]=='S')M[i][j]='0';
      }
    }
    cout << solve(H,W,N,M) << endl;
  }
  return 0;
}

C++: #include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int Max=1000+9;
char a[Max][Max];
bool vis[Max][Max];
int n,m,num;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
struct node{
    int x,y,t;
    int path;
};
int bfs(int x,int y,int t){
    memset(vis,0,sizeof(vis));
    queue<node> q;
    q.push(node{x,y,t,0});
    while(!q.empty()){
        int cx=q.front().x;
        int cy=q.front().y;
        int ct=q.front().t;
        int path=q.front().path;
        q.pop();
        for(int i=0;i<4;i++){
            int nx=cx+dx[i];
            int ny=cy+dy[i];
            if(nx<1||nx>n||ny<1||ny>m||vis[nx][ny]||a[nx][ny]=='X'){
                continue;
            }
            vis[nx][ny]=1;
            if(a[nx][ny]==ct+'0'){
                //cout<<nx<<"!!"<<ny<<"!!"<<ct<<"!!"<<path<<endl;
                if(ct==num){
                    return path+1;
                }
                return bfs(nx,ny,ct+1)+path+1;
            }else{
                q.push(node{nx,ny,ct,path+1});
            }
        }
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    cin>>num;
    int sx,sy;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>a[i][j];
            if(a[i][j]=='S'){
                sx=i;
                sy=j;
            }
        }
    }
    cout<<bfs(sx,sy,1)<<endl;
    return 0;
}