Problem:
Problem F: Cleaning Robot Here, we want to solve path planning for a mobile robot cleaning a
rectangular room floor with furniture. Consider the room floor paved with square tiles whose size fits 
the cleaning robot (1 × 1).
There are 'clean tiles' and 'dirty tiles', and the robot can change
a 'dirty tile' to a 'clean tile' by visiting the tile.
Also there may be some obstacles (furniture) whose size fits a
tile in the room. If there is an obstacle on a tile, the robot cannot visit 
it.
The robot moves to an adjacent tile with one move.
The tile onto which the robot moves must be one of four tiles 
(i.e., east, west, north or south) adjacent to the tile where the 
robot is present. The robot may visit a tile twice or more. Your task is to write a program which computes the minimum number of
moves for the robot to change all 'dirty tiles' to 'clean tiles', 
if ever possible. Input The input consists of multiple maps, each representing the size 
and arrangement of the room. A map is given in the following format.  w h   c 11  c 12  c 13 ... c 1 w  c 21  c 22  c 23 ... c 2 w ...  c h 1  c h 2  c h 3 ... c hw   The integers w and h are the lengths of the two sides 
of the floor of the room in terms of widths of floor tiles. w and h are less than or equal to 20. The character c yx represents 
what is initially on the tile with coordinates ( x, y ) as follows. ' . ' : a clean tile ' * ' : a dirty tile ' x ' : a piece of furniture (obstacle) ' o ' : the robot (initial position)  In the map the number of 'dirty tiles' does not exceed 10.
There is only one 'robot'. The end of the input is indicated by a line containing two zeros. Output For each map, your program should output a line containing the minimum 
number of moves. If the map includes 'dirty tiles' which the robot cannot reach, 
your program should output -1. Sample Input 7 5
.......
.o...*.
.......
.*...*.
.......
15 13
.......x.......
...o...x....*..
.......x.......
.......x.......
.......x.......
...............
xxxxx.....xxxxx
...............
.......x.......
.......x.......
.......x.......
..*....x....*..
.......x.......
10 10
..........
..o.......
..........
..........
..........
.....xxxxx
.....x....
.....x.*..
.....x....
.....x....
0 0 Output for the Sample Input 8
49
-1

Solution (Python):
from collections import deque
dd = [(-1, 0), (0, -1), (1, 0), (0, 1)]
while 1:
    w, h = map(int, raw_input().split())
    if w == 0:
        break
    C = [raw_input() for i in xrange(h)]
    cnt = 0
    mark = {}
    sx = sy = -1
    for i in xrange(h):
        for j in xrange(w):
            if C[i][j] == 'o':
                sx = j; sy = i
            elif C[i][j] == '*':
                mark[j, i] = cnt
                cnt += 1
    ALL = 2**cnt - 1
    dis = {(sx, sy, 0): 0}
    deq = deque()
    deq.append((sx, sy, 0))
    ans = -1
    while deq and ans == -1:
        x, y, state = key = deq.popleft()
        for dx, dy in dd:
            nx = x + dx
            ny = y + dy
            if 0 <= nx < w and 0 <= ny < h and C[ny][nx] != 'x':
                n_state = state
                if C[ny][nx] == '*':
                    n_state |= 1 << mark[nx, ny]
                if n_state == ALL:
                    ans = dis[key] + 1
                    break
                n_key = (nx, ny, n_state)
                if n_key not in dis:
                    dis[n_key] = dis[key] + 1
                    deq.append(n_key)
    print ans

Solution (Python):
import sys
from heapq import heappush, heappop
sys.setrecursionlimit(100000)
INF = 10 ** 10

direct = ((0, -1), (0, 1), (-1, 0), (1, 0))

def dist(fr, to, mp):
  que = []
  heappush(que, (0, fr))
  visited = [[False] * len(mp[0]) for _ in range(len(mp))]
  visited[fr[1]][fr[0]] = True
  while que:
    d, point = heappop(que)
    x, y = point
    for dx, dy in direct:
      nx, ny = x + dx, y + dy
      if (nx, ny) == to:
        return d + 1
      if not visited[ny][nx] and mp[ny][nx] != "x":
        visited[ny][nx] = True
        heappush(que, (d + 1, (nx, ny)))
  else:
    return -1

def my_hash(rest):
  return sum([10 ** i for i in rest])

def shortest(fr, rest, edges, dp):
  if rest == set():
    return 0
  if my_hash(rest) in dp[fr]:
    return dp[fr][my_hash(rest)]
  ret = INF
  for d, to in edges[fr]:
    if to in rest:
      score = d + shortest(to, rest - {to}, edges, dp)
      if score < ret:
        ret = score
  dp[fr][my_hash(rest)] = ret
  return ret

def main():
  while True:
    w, h = map(int, input().split())
    if w == 0:
      break
    mp = ["x" + input() + "x" for _ in range(h)]
    mp.insert(0, "x" * (w + 2))
    mp.append("x" * (w + 2))
    
    stains = []
    for y in range(1, h + 1):
      for x in range(1, w + 1):
        if mp[y][x] == "*":
          stains.append((x, y))
        elif mp[y][x] == "o":
          start = len(stains)
          stains.append((x, y))
    
    stain_num = len(stains)
    edges = [[] for _ in range(stain_num)]
    D = [[None] * stain_num for _ in range(stain_num)]
    for i in range(stain_num):
      D[i][i] = 0
    miss_flag = False
    for i in range(stain_num):
      for j in range(i + 1, stain_num):
        fr = stains[i]
        to = stains[j]
        d = dist(fr, to, mp)
        if d == -1:
          miss_flag = True
        edges[i].append((d, j))
        edges[j].append((d, i))
        D[i][j] = d
        D[j][i] = d
    if miss_flag:
      print(-1)
      continue


    dp = [{} for _ in range(10)]
    print(shortest(start, {i for i in range(stain_num) if i != start}, edges, dp))
main()

Solution (Python):
from heapq import heappush, heappop
INF = 10 ** 10

direct = ((0, -1), (0, 1), (-1, 0), (1, 0))

def dist(fr, to, mp):
  que = []
  heappush(que, (0, fr))
  visited = [[False] * len(mp[0]) for _ in range(len(mp))]
  visited[fr[1]][fr[0]] = True
  while que:
    d, point = heappop(que)
    x, y = point
    for dx, dy in direct:
      nx, ny = x + dx, y + dy
      if (nx, ny) == to:
        return d + 1
      if not visited[ny][nx] and mp[ny][nx] != "x":
        visited[ny][nx] = True
        heappush(que, (d + 1, (nx, ny)))
  else:
    return -1

def my_hash(rest):
  return sum([10 ** i for i in rest])

def shortest(fr, rest, edges, dp):
  if rest == set():
    return 0
  if my_hash(rest) in dp[fr]:
    return dp[fr][my_hash(rest)]
  ret = INF
  for d, to in edges[fr]:
    if to in rest:
      score = d + shortest(to, rest - {to}, edges, dp)
      if score < ret:
        ret = score
  dp[fr][my_hash(rest)] = ret
  return ret

def main():
  while True:
    w, h = map(int, input().split())
    if w == 0:
      break
    mp = ["x" + input() + "x" for _ in range(h)]
    mp.insert(0, "x" * (w + 2))
    mp.append("x" * (w + 2))
    
    stains = []
    for y in range(1, h + 1):
      for x in range(1, w + 1):
        if mp[y][x] == "*":
          stains.append((x, y))
        elif mp[y][x] == "o":
          start = len(stains)
          stains.append((x, y))
    
    stain_num = len(stains)
    edges = [[] for _ in range(stain_num)]
    miss_flag = False
    for i in range(stain_num):
      for j in range(i + 1, stain_num):
        fr = stains[i]
        to = stains[j]
        d = dist(fr, to, mp)
        if d == -1:
          miss_flag = True
        edges[i].append((d, j))
        edges[j].append((d, i))
    if miss_flag:
      print(-1)
      continue

    dp = [{} for _ in range(stain_num)]
    print(shortest(start, {i for i in range(stain_num) if i != start}, edges, dp))

main()

Solution (Python):
from heapq import heappush, heappop
INF = 10 ** 10

direct = ((0, -1), (0, 1), (-1, 0), (1, 0))

def dist(fr, to, mp):
  que = []
  heappush(que, (0, fr))
  visited = [[False] * len(mp[0]) for _ in range(len(mp))]
  visited[fr[1]][fr[0]] = True
  while que:
    d, point = heappop(que)
    x, y = point
    for dx, dy in direct:
      nx, ny = x + dx, y + dy
      if (nx, ny) == to:
        return d + 1
      if not visited[ny][nx] and mp[ny][nx] != "x":
        visited[ny][nx] = True
        heappush(que, (d + 1, (nx, ny)))
  else:
    return -1

def my_hash(rest):
  ret = 0
  for i in rest:
    ret += 10 ** i
  return ret

def shortest(fr, rest, edges, dp):
  if rest == set():
    return 0
  h = my_hash(rest)
  if h in dp[fr]:
    return dp[fr][h]
  ret = INF
  for d, to in edges[fr]:
    if to in rest:
      score = d + shortest(to, rest - {to}, edges, dp)
      if score < ret:
        ret = score
  dp[fr][h] = ret
  return ret

def main():
  while True:
    w, h = map(int, input().split())
    if w == 0:
      break
    mp = ["x" + input() + "x" for _ in range(h)]
    mp.insert(0, "x" * (w + 2))
    mp.append("x" * (w + 2))
    
    stains = []
    for y in range(1, h + 1):
      for x in range(1, w + 1):
        if mp[y][x] == "*":
          stains.append((x, y))
        elif mp[y][x] == "o":
          start = len(stains)
          stains.append((x, y))
    
    stain_num = len(stains)
    edges = [[] for _ in range(stain_num)]
    miss_flag = False
    for i in range(stain_num):
      for j in range(i + 1, stain_num):
        fr = stains[i]
        to = stains[j]
        d = dist(fr, to, mp)
        if d == -1:
          miss_flag = True
        edges[i].append((d, j))
        edges[j].append((d, i))
    if miss_flag:
      print(-1)
      continue

    dp = [{} for _ in range(stain_num)]
    print(shortest(start, {i for i in range(stain_num) if i != start}, edges, dp))

main()

Solution (Python):
import sys
import math
import bisect
import heapq
import copy
sys.setrecursionlimit(1000000)
from collections import deque
from itertools import permutations

dy = [-1,0,1,0]
dx = [0,1,0,-1]

def main():
    m,n = 0,0
    grid = []
    inf = 1000000007

    def in_the_grid(h,w):
        return 0<=h and h<n  and 0<=w and w<m

    def bfs(i,j):
        dq = deque()
        res = [[inf]*m for _ in range(n)]
        dq.append([i,j,0])
        res[i][j] = 0
        while dq:
            h,w,c = dq.popleft()
            for k in range(4):
                n_h = h+dy[k]
                n_w = w+dx[k]
                if not in_the_grid(n_h,n_w):continue
                if grid[n_h][n_w] == 'x':continue
                if res[n_h][n_w]!=inf:continue
                res[n_h][n_w] = c+1
                dq.append([n_h,n_w,c+1])
        return res

    while True:
        m,n = map(int,input().split())
        if m == 0:break
        grid = []
        dis = []
        ver = []
        for _ in range(n):
            grid.append(input())
        for i in range(n):
            for j in range(m):
                if grid[i][j]=='o':
                    ver.append([i,j])
                    dis.append(bfs(i,j))
        for i in range(n):
            for j in range(m):
                if grid[i][j]=='*':
                    ver.append([i,j])
                    dis.append(bfs(i,j))

        v = len(dis)
        d = [[] for _ in range(v)]
        for i in range(v):
            for j,k in ver:
                d[i].append(dis[i][j][k])

        dp = [[inf]*v for _ in range(1<<v)]
        dp[1][0] = 0
        for bits in range(1<<v):
            for i in range(v):
                if dp[bits][i] == inf:continue
                for j in range(v):
                    if bits&(1<<j):continue
                    dp[bits|(1<<j)][j] = min(dp[bits|(1<<j)][j],
                                             dp[bits][i]+d[i][j])

        ans = inf
        for i in range(1,v):ans = min(ans,dp[(1<<v)-1][i])
        print (ans if ans!=inf else -1)


if __name__ == '__main__':
    main()

Solution (Python):


from collections import deque
from itertools import permutations

dx = [1,0,-1,0]
dy = [0,1,0,-1]

def bfs(sy,sx):
    dist = [[-1]*w for _ in range(h)]
    que = deque()
    que.append((sy,sx))
    dist[sy][sx] = 0
    while que:
        y,x = que.popleft()
        for i in range(4):
            nx,ny = x+dx[i],y+dy[i]
            if 0 <= nx < w and 0 <= ny < h:
                if dist[ny][nx] < 0 and M[ny][nx] != "x":
                    dist[ny][nx] = dist[y][x] + 1
                    que.append((ny,nx))

    return dist

while 1:
    w,h = map(int,input().split())
    if w == 0 and h == 0:
        break
    M = [list(input()) for _ in range(h)]
    p = []
    for i in range(h):
        for j in range(w):
            if M[i][j] == "o":
                p.append((i,j))
                break
    for i in range(h):
        for j in range(w):
            if M[i][j] == "*":
                p.append((i,j))
    
    n = len(p)
    dist = [[float("inf")]*n for _ in range(n)]
    f = 0
    for i in range(n):
        di = bfs(*p[i])
        for j in range(n):
            dist[i][j] = di[p[j][0]][p[j][1]]
            if dist[i][j] < 0:
                f = 1
                break
    
    if f:
        print(-1)
        continue

    
    po = [1<<i for i in range(11)]
    ma = po[n]
    dp = [[float("inf")]*(n) for _ in range(ma)]
    dp[1][0] = 0
    for b in range(ma):
        for j in range(n):
            if b&po[j]:
                continue
            nb = b|po[j]
            for i in range(n):
                if not b&po[i]:
                    continue
                
                if dp[nb][j] > dp[b][i] + dist[i][j]:
                    dp[nb][j] = dp[b][i] + dist[i][j]
    print(min(dp[ma - 1]))

Solution (Python):
import sys
from collections import deque
d = [(1,0),(-1,0),(0,1),(0,-1)]
def bfs(sy,sx): 
    dist = [[-1]*w for i in range(h)]
    dist[sy][sx] = 0
    q = deque([(sy,sx)])
    while q:
        y,x = q.popleft()
        for dy,dx in d:
            y_ = y+dy
            x_ = x+dx
            if 0 <= y_ < h and 0 <= x_ < w:
                if dist[y_][x_] < 0 and s[y_][x_] != "x":
                    dist[y_][x_] = dist[y][x] + 1
                    q.append((y_,x_))
    return dist

po = [1<<i for i in range(11)] 
while 1:
    w,h = map(int, sys.stdin.readline().split())
    if w == 0:
        break
    s = [sys.stdin.readline() for i in range(h)]
    p = [] 
    for y in range(h):
        for x in range(w):
            if s[y][x] == "o":
                p.append((y,x))
                break
    for y in range(h):
        for x in range(w):
            if s[y][x] == "*":
                p.append((y,x))
    """↑スタートの座標を常にp[0]に保存したかったからこうやってループを分けた"""
    n = len(p)
    dist = [[float("inf")]*n for i in range(n)] 
    f = 0
    for i in range(n):
        di = bfs(*p[i]) 
        for j in range(n):
            dist[i][j] = di[p[j][0]][p[j][1]]
            if dist[i][j] < 0:
                f = 1 
                break
    if f:
        print(-1)
        continue
    """以下bitDP"""
    ma = po[n] 
    dp = [[float("inf")]*(n) for i in range(ma)] 
    dp[1][0] = 0
    for b in range(ma): 
        for j in range(n):
            if (b&po[j]):continue 
            b_ = b|po[j] 
            for i in range(n):
                if not b&po[i]:continue
                
                if dp[b_][j] > dp[b][i]+dist[i][j]:
                    dp[b_][j] = dp[b][i]+dist[i][j]
    print(min(dp[ma-1]))

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []

    def f(w,h):
        a = ['x'*(w+2)] + ['x' + S() + 'x' for _ in range(h)] + ['x'*(w+2)]
        e = collections.defaultdict(list)
        st = None
        dst = []
        for i in range(1,h+1):
            for j in range(1,w+1):
                if a[i][j] == 'x':
                    continue
                if a[i][j] == 'o':
                    st = (i,j)
                elif a[i][j] == '*':
                    dst.append((i,j))
                for di,dj in dd:
                    if a[i+di][j+dj] == 'x':
                        continue
                    e[(i,j)].append(((i+di,j+dj), 1))

        def search(s):
            d = collections.defaultdict(lambda: inf)
            d[s] = 0
            q = []
            heapq.heappush(q, (0, s))
            v = collections.defaultdict(bool)
            while len(q):
                k, u = heapq.heappop(q)
                if v[u]:
                    continue
                v[u] = True

                for uv, ud in e[u]:
                    if v[uv]:
                        continue
                    vd = k + ud
                    if d[uv] > vd:
                        d[uv] = vd
                        heapq.heappush(q, (vd, uv))

            return d

        sd = search(st)
        for ds in dst:
            if sd[ds] == inf:
                return -1

        dsd = [search(ds) for ds in dst]
        l = len(dst)
        r = inf
        for ta in itertools.permutations(range(l)):
            t = sd[dst[ta[0]]]
            for i in range(l-1):
                t += dsd[ta[i]][dst[ta[i+1]]]
            if r > t:
                r = t

        return r

    while 1:
        n,m = LI()
        if n == 0 and m == 0:
            break
        rr.append(f(n,m))
        

    return '\n'.join(map(str,rr))


print(main())