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 <stdio.h>
#include <cstring>
#include <queue>
using namespace std;

char ma[1005][1005];int vis[1005][1005];
int w,h,n;

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

struct node
{
    int x,y,time;
};
node start;

void bfs(char ed)
{
    queue<node> que;
    que.push(start);
    vis[start.x][start.y]=1;
    while(!que.empty())
    {
        node no=que.front();
        que.pop();
        for(int i=0;i<4;i++)
        {
            int x=no.x+dx[i];
            int y=no.y+dy[i];
            if(vis[x][y]||x>=h||x<0||y>=w||y<0||ma[x][y]=='X')
                continue;
            if(ma[x][y]==ed)
            {
                start.x=x;
                start.y=y;
                start.time=no.time+1;
                return ;
            }
            vis[x][y]=1;
            node no1;
            no1.x=x;no1.y=y;no1.time=no.time+1;
            que.push(no1);
        }
    }
}

int main()
{
    while(scanf("%d %d %d\n", & h, & w, & n))
    {
        for(int i=0;i<h;i++)
        {
            scanf("%s",&ma[i]);
            for(int j=0;j<w;j++)
                if(ma[i][j]=='S')
                {
                    start.x=i;
                    start.y=j;
                    start.time=0;
                }

        }
            for(int i=0;i<n;i++)
            {
                memset(vis,0,sizeof(vis));
                bfs(i+'1');
            }

            printf("%d\n",start.time);
    }
    return 0; 
}

C++: #include <bits/stdc++.h>
#include <ctype.h>
using namespace std;

typedef pair<int, int> P;

const int INF = 1<<10;

int H, W, N;
char field[1010][1010];
int dx[4] = {0,0,1,-1}, dy[4] = {1,-1,0,0};
int tim[1010][1010];
int sx, sy;
int cnt;
int hp = 1;

int bfs() {
  for (int i = 1; i <= N; i++) {
    bool flag = false;
    queue<P> q;
    for (int y = 0; y < H; y++)
      for (int x = 0; x < W; x++) tim[y][x] = INF;
    q.push(P(sx, sy));
    tim[sy][sx] = 0;

    while (!q.empty() && !flag) {
      int x = q.front().first;
      int y = q.front().second;
      int c = tim[y][x];
      q.pop();
      for (int j = 0; j < 4; j++) {
        int tx = x + dx[j], ty = y + dy[j];
        if (tx < 0 || ty < 0 || tx >= W || ty >= H ||
            tim[ty][tx] != INF || field[ty][tx] == 'X') continue;
        if (field[ty][tx] == '0' + i) {
          cnt += c + 1;
          sx = tx; sy = ty;
          flag = true;
          break;
        }
        tim[ty][tx] = c + 1;
        q.push(P(tx, ty));
      }
    }
  }
}

int main() {
  cin >> H >> W >> N;
  for (int y = 0; y < H; y++) {
    cin >> field[y];
    for (int x = 0; x < W; x++) {
      if (field[y][x] == 'S') {
        sx = x; sy = y;
        field[y][x] = '.';
      }
    }
  }

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

struct P {int x,y;};

using namespace std;

char map[1005][1005];
int h,w,n;

int distance(char start, char goal) {
    queue<pair<P,int> > q;
    for(int i=0;i<h;i++)
        for(int j=0;j<w;j++)
            if(map[i][j] == start) q.push(pair<P,int>({j,i}, 0));
    
    while(!q.empty()) {
        pair<P,int> t = q.front(); q.pop();
        struct P p = t.first;
        int d = t.second;

        if(p.x < 0 || p.y < 0 || p.x >= w || p.y >= h) continue;
        if(map[p.y][p.x] == 'X') continue;
        if(map[p.y][p.x] == goal) return d;
        map[p.y][p.x] = 'X';
        
        q.push(pair<P,int>({p.x+1,p.y},d+1));
        q.push(pair<P,int>({p.x,p.y+1},d+1));
        q.push(pair<P,int>({p.x-1,p.y},d+1));
        q.push(pair<P,int>({p.x,p.y-1},d+1));
    }
    return -1;
}


int main(void) {
    int res=0;

    scanf("%d%d%d",&h,&w,&n);
    for(int i=0;i<h;i++)
        scanf("%s",map[i]);
    res += distance('S','1');
    for(int i=1;i<n;i++)
        res += distance('0'+i,'1'+i);

    printf("%d\n",res);

    return 0;
}

C++: // AOJ 0558
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<queue>
#include<map>
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define X first
#define Y second
using namespace std;

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

int H, W, N;
const int HMAX = 1008, WMAX = 1008;
char field[HMAX][WMAX];

bool legal(P p) {
  return 0 <= p.X and p.X < W and 0 <= p.Y and p.Y < H
    and field[p.X][p.Y] != 'X';
}

const int INF = 1e7;
int dist[HMAX][WMAX];

int distance(P start, P goal) {
  priority_queue<S, vector<S>, greater<S> > que;
  REP(x,W) REP(y,H) { dist[x][y] = INF; }

  dist[start.X][start.Y] = 0;
  que.push(S(0, start));

  while (!que.empty()) {
    S state = que.top(); que.pop();
    P cur = state.second;
    if (dist[cur.X][cur.Y] < state.first) continue;
    
    const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
    REP(i, 4) {
      P p = P(cur.X + dx[i], cur.Y + dy[i]);
      if (legal(p) and dist[p.X][p.Y] > dist[cur.X][cur.Y] + 1) {
        dist[p.X][p.Y] = dist[cur.X][cur.Y] + 1;
        que.push(S(dist[p.X][p.Y], p));
      }
    }
  }
  return dist[goal.X][goal.Y];
}

P search(char c) {
  REP(y, H) REP(x, W) {
    if (field[x][y] == c)
      return P(x, y);
  }
}

int solve() {
  int ans = 0;
  P start = search('S');
  for (int i = 1; i <= N; i++) {
    P goal = search('0' + i);
    ans += distance(start, goal);
    start = goal;
  }
  return ans;
}

int main() {
  cin >> H >> W >> N;
  REP(y, H) {
    string row;
    cin >> row;
    REP(x, W) {
      field[x][y] = row[x];
    }
  }

  cout << solve() << endl;
}

C++: #include <cstdio>
#include <cstring>

char map[1000][1000];
int h,w,res;

void dfs(int x, int y, char c) {
    if(x<0 || y<0 || x>=w || y>=h) return;
    if(map[y][x] == c) {
        map[y][x] = '.';
        dfs(x-1,y,c); dfs(x,y-1,c);
        dfs(x+1,y,c); dfs(x,y+1,c);
    }
}

int main(void) {
    while(true) {
        res = 0;
        memset(map, 0, sizeof(map));

        scanf("%d%d",&h,&w);
        if(!h && !w) break;
        for(int i=0; i<h; i++) scanf("%s",map[i]);

        for(int i=0; i<h; i++)
            for(int j=0; j<w; j++)
                if(map[i][j] != '.') {
                    res++;
                    dfs(j, i, map[i][j]);
                }
        printf("%d\n", res);

    }
    return 0;
}