多次BFS
#include <bits/stdc++.h>
using namespace std;
const int N = 310;
char g[N][N];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
bool st[N][N];
int main()
{
int n, m;
while (cin >> n >> m, n && m) {
memset(st, 0, sizeof st);
pair<int,int> beg, ed;
for (int i = 0 ; i < n ; i ++ ) {
for (int j = 0 ; j < m ; j ++ ) {
cin >> g[i][j];
if (g[i][j] == '@') beg = {i, j};
if (g[i][j] == '*') ed = {i, j};
}
}
queue<pair<int,int>> q;
q.push(beg);
int ans = 0;
st[beg.first][beg.second] = true;
bool f = false;
while (q.size()) {
int l = q.size();
for (int i = 0 ; i < l ; i ++ ) {
auto t = q.front();
if (t == ed) {
f = true;
break;
}
q.pop();
for (int j = 0 ; j < 4 ; j ++ ) {
int x = t.first + dx[j];
int y = t.second + dy[j];
if (x >= 0 && x < n && y >= 0 && y < m && !st[x][y] && g[x][y] != '#') {
q.push({x, y});
st[x][y] = true;
}
}
}
if (f) break;
ans ++ ;
}
if (f) cout << ans << endl;
else cout << -1 << endl;
}
return 0;
}