#include<iostream> #include<string> #include<vector> #include<queue> using namespace std; const int maxn = 100; struct nod { int x, y; int step; }node; int n, m,fx,fy; vector<string>a; bool inq[maxn][maxn] = { false }; bool judge(int x,int y) { if (x < 0 || y < 0 || x >= n || y >= m) return false; if (inq[x][y] == true || a[x][y] == '*') return false; return true; } int X[] = { 0,0,1,-1 }; int Y[] = { 1,-1,0,0 }; int BFS(int x, int y,int d) { queue<nod>q; node.x = x; node.y = y; node.step = d; q.push(node); inq[x][y] = true; int nowx, nowy, nows; while (!q.empty()) { nod temp = q.front(); q.pop(); if (temp.x == fx && temp.y == fy) return temp.step; for (int i = 0; i < 4; i++) { nowx = temp.x + X[i]; nowy = temp.y + Y[i]; nows = temp.step+1; if (judge(nowx, nowy)) { node.x = nowx; node.y = nowy; node.step = nows; q.push(node); inq[nowx][nowy] = true; } } } return -1; } int main() { FILE* streaml; freopen_s(&streaml, "input.txt", "r", stdin); cin >> n >> m; getchar(); string s; for (int i = 0; i < n; i++) { getline(cin, s); a.push_back(s); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) if (a[i][j] == 'D')//找到终点坐标 { fx = i; fy = j; break; } } int dis; for (int i = 0; i < n; i++) { for(int j=0;j<m;j++) if (a[i][j] == 'S') { dis = BFS(i, j, 0); break; } } cout << dis << endl; return 0; }