#include using namespace std; int n, m; pair start; pair finish; char mat[1001][1001]; bool used[1001][1001]; int dist[1001][1001]; int leftWall[1001][1001]; int rightWall[1001][1001]; int topWall[1001][1001]; int bottomWall[1001][1001]; int op[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; void input() { scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) { scanf("%s", mat[i]); for (int j = 0; j < m; j++) { if (mat[i][j] == 'S') { start = {i, j}; } if (mat[i][j] == 'F') { finish = {i, j}; } } } } void prepare() { for (int i = 0; i < n; i++) { int c = 0; for (int j = 0; j < m; j++) { if (mat[i][j] == '#') c = j; else leftWall[i][j] = c + 1; } c = m - 1; for (int j = m - 1; j >= 0; j--) { if (mat[i][j] == '#') c = j; else rightWall[i][j] = c - 1; } } for (int j = 0; j < m; j++) { int r = 0; for (int i = 0; i < n; i++) { if (mat[i][j] == '#') r = i; else topWall[i][j] = r + 1; } r = n - 1; for (int i = n - 1; i >= 0; i--) { if (mat[i][j] == '#') r = i; else bottomWall[i][j] = r - 1; } } } int solve() { queue> q; q.push(start); used[start.first][start.second] = true; while (q.empty() == false) { pair node = q.front(); q.pop(); int r = node.first; int c = node.second; for (int i = 0; i < 4; i++) { int newr = r + op[i][0]; int newc = c + op[i][1]; if (newr < 0 or newr >= n or newc < 0 or newc >= m) { continue; } if (used[newr][newc] or mat[newr][newc] == '#') { continue; } dist[newr][newc] = dist[r][c] + 1; q.push({newr, newc}); used[newr][newc] = true; } if (!used[r][leftWall[r][c]]) { dist[r][leftWall[r][c]] = dist[r][c] + 1; q.push({r, leftWall[r][c]}); used[r][leftWall[r][c]] = true; } if (!used[r][rightWall[r][c]]) { dist[r][rightWall[r][c]] = dist[r][c] + 1; q.push({r, rightWall[r][c]}); used[r][rightWall[r][c]] = true; } if (!used[topWall[r][c]][c]) { dist[topWall[r][c]][c] = dist[r][c] + 1; q.push({topWall[r][c], c}); used[topWall[r][c]][c] = true; } if (!used[bottomWall[r][c]][c]) { dist[bottomWall[r][c]][c] = dist[r][c] + 1; q.push({bottomWall[r][c], c}); used[bottomWall[r][c]][c] = true; } if (used[finish.first][finish.second]) { return dist[finish.first][finish.second]; } } return -1; } int main() { input(); prepare(); printf("%d\n", solve()); return 0; } /* ######### #...#...# #.#...#.# #.#...#.# #..###..# ##.....## ###...### #.......# #..###..# #.#...#.# #.#...#.# #...#...# */