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 <vector>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <functional>
#include <cstdio>
#include <deque>
using namespace std;

#define START 'S'
#define CANTGO 'X'
#define NONE '.'
#define FINUM field[i][j] - '0'

struct Point
{
	int x;
	int y;
};

int dx[] = {0,-1,0,1};//ã©çvñè
int dy[] = {1,0,-1,0};
string field[1000];
int mfield[1001][1001] = {};
int life=1;
int counter=0;
int csum = 0;
int H,W,N;


int open(deque<Point> &tp)
{
	counter++;
	int i,j;
	Point inp;
	int size = tp.size();

	for(i=0;i<size;i++)
	{
		for(j=0;j<4;j++)
		{
			inp.x = tp[i].x+dx[j];
			inp.y = tp[i].y+dy[j];
			if(inp.x<0 || inp.y<0 || inp.x>=H || inp.y>=W)
				continue;
			if(field[inp.x][inp.y] != CANTGO && field[inp.x][inp.y] != START  && mfield[inp.x][inp.y] != life)
			{
				//v·éÉÅZ£Ú®Â\][
				if(field[inp.x][inp.y] == life + '0' ) //©ªÉ©Á½`[YÌ­©
				{
					tp.clear();
					tp.push_back(inp);
					return counter;
				}
				else
				{
					tp.push_back(inp);
					mfield[inp.x][inp.y] = life;
				}
			}
		}
	}
	tp.erase(tp.begin(),tp.begin()+size);
	//copy(tp.begin() , tp.end() , tp.begin());
	return 0;
}

int main(void)
{
	int i,j;
	deque<Point> tp;
	Point inp;
	Point gool;
	int count = 0;
	cin >> H >> W >> N;

	for(i=0;i<H;i++)//üÍ
	{
		cin >> field[i];
		for(j=0;j<W;j++)
		{
			if(field[i][j] == 'S')
			{
				inp.x = i;
				inp.y = j;
				tp.push_back(inp);
				mfield[inp.x][inp.y] = life;
			}
		}
	}//üÍIíè

	while(1)
	{
		if(open(tp) != 0)
		{
			life++;
			csum += counter;
			counter = 0;
		}
		if(life > N)
			break;
	}
		cout << csum << endl;

	return 0;
}

C++: #include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <climits>
#include <queue>
#include <iostream>


#define MAX_H 1100
#define MAX_W 1100


struct status
{
  int x;
  int y;
  int step;
  int n;
};


int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

  
int H,W,N;
char maze[MAX_H][MAX_W];
int flag[MAX_H][MAX_W];
int xs,ys;
std::queue<status> Q;


int BFS();

int main(int argc, char* argv[])
{
  //freopen("in.txt","r",stdin);
  while(std::cin>>H>>W>>N)
    {

      std::cin.get();
      //std::cout << H << W << N << std::endl;

      for(int i = 0 ; i < H ; i++)
	std::cin.getline(maze[i],MAX_W);

      //for(int i = 0 ; i < H ; i++)
      //	std::cout << maze[i] << std::endl;

      for(int j = 0 ; j < H ; j++)
	for(int i = 0 ; i < W ; i++)
	  if(maze[j][i] == 'S' )
	    {
	      xs = i;
	      ys = j;
	      break;
	    }
      memset(flag,0,sizeof(flag));
      std::cout<<BFS()<<std::endl;
      
    }
}


int BFS()
{

  while(Q.empty()==false)
    Q.pop();
  status start;
  start.x = xs;
  start.y = ys;
  start.step = 0;
  start.n = 1;

  Q.push(start);

  while(Q.empty() == false )
    {
      status tmp = Q.front();
      Q.pop();


      for(int i = 0 ; i < 4 ; i++)
	{
	  int cx = tmp.x + dx[i];
	  int cy = tmp.y + dy[i];
	  int cstep = tmp.step + 1;
	  int cn = tmp.n;

	  if(cx < 0 || cx >= W ) continue;
	  if(cy < 0 || cy >= H ) continue;
	  if(maze[cy][cx] == 'X' ) continue;

	  if( (maze[cy][cx] - '0') == tmp.n )
	    cn = tmp.n + 1;
	  else
	    cn = tmp.n;

	  if(cn == N+1)
	    return cstep;

	  
	  
	  if(flag[cy][cx] >= cn  ) continue;

	  flag[cy][cx] = cn;

	  status nstatus;
	  nstatus.x = cx;
	  nstatus.y = cy;
	  nstatus.n = cn;
	  nstatus.step = cstep;
	  Q.push(nstatus);
	  
	}
    }

  return -1;
  
}

C++: #include<iostream>
#include<iomanip>
#include<fstream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<complex>
#include<set>
#include<map>
#include<list>
#include<vector>
#include<deque>
using namespace std;
typedef long long ll;
typedef vector<int>vec;
typedef vector<vec>mat;
const int INF = 0x3f3f3f3f;
const int Mod = 1e9 + 7;
const double eps = 1e-7;
int dirX[4] = { 1,0,-1,0 };
int dirY[4] = { 0,1,0,-1 };
struct point {
	int x; int y; int depth;
	point() { x = y = depth=0; }
	point(int X, int Y, int D) { x = X; y = Y; depth = D; }
	point(const point &p) { x = p.x; y = p.y; depth = p.depth; }
	bool operator==(const point&C) {
		return{x==C.x&&y==C.y};
	}
};
struct cheese :public point {
	int hard;
	cheese() { x = y = hard = 0; }
	cheese(int X, int Y, int H) { x = X; y = Y; hard = H; }
	bool operator<(const cheese&C) {
		return hard < C.hard;
	}
};
int main() {
	//ifstream ifs;
	//ifs.open("D:\\documents\\programDatas\\AOJ0558.txt");
	int H, W, N;
	cin >> H >> W >> N;
	bool a[1001][1001]; bool v[1001][1001];//here???
	memset(a, 0, sizeof(a)); memset(v, 0, sizeof(v));
	vector<cheese>goal;
	for (int i = 1; i <= H; i++) {
		for (int j = 1; j <= W; j++) {
			char temp;
			cin >> temp;
			if (temp == 'S')goal.push_back(cheese(i, j, 0));
			else if (temp >= '1'&&temp <= '9')goal.push_back(cheese(i, j, (int)(temp - 48)));
			else if (temp == '.')a[i][j] = 0;
			else if (temp == 'X')a[i][j] = 1;
		}
	}
	sort(goal.begin(), goal.end());
	//for debug
	/*for (int i = 1; i <= H; i++) {
		for (int j = 1; j <= W; j++) {
			cout << setw(3) << a[i][j];
		}
		cout << endl;
	}
	for (int i = 0; i <= N; i++) {
		cout << goal[i].x << " " << goal[i].y << " " << goal[i].hard << " " << endl;
	}
	cout << endl;
	*/
	//BFS
	int total = 0;//total steps
	for (int t = 0; t < N; t++) {//x for start point and x+1 for end point
		deque<point>que;
		que.push_back(point(goal[t].x, goal[t].y, 0));
		//for (int s = t + 2; s <= N; s++) {//mark harder cheese as visited !!
		//	v[goal[s].x][goal[s].y] = 1;
		//}
		while (!que.empty()) {

			point curP = que.front();
			que.pop_front();
			v[curP.x][curP.y] = 1;//as visited
			if (curP == goal[t + 1]) {
				total = total + curP.depth ;
				memset(v, 0, sizeof(v));
				break;
			}
			else {
				for (int i = 0; i < 4; i++) {
					int tx = curP.x + dirX[i];
					int ty = curP.y + dirY[i];
					if (tx >= 1 && tx <= H&&ty >= 1 && ty <= W&&a[tx][ty]==0&&v[tx][ty] == 0)
						que.push_back(point(tx, ty, curP.depth + 1));
				}
			}
		}
	}
	cout << total << endl;
	return 0;
}