public class RobotOnMoon
{
public int LongestSafeCommand
(String[] board
) {
int n = board.length, m = board[0].length();
int x = 0, y = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(board[i].charAt(j) == 'S')
{
x = i;
y = j;
}
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(board[i].charAt(j) == '#' && (i == x || j == y))
return -1;
return n + m - 2;
}
}
cHVibGljIGNsYXNzIFJvYm90T25Nb29uCnsKCXB1YmxpYyBpbnQgTG9uZ2VzdFNhZmVDb21tYW5kKFN0cmluZ1tdIGJvYXJkKQoJewoJCWludCBuID0gYm9hcmQubGVuZ3RoLCBtID0gYm9hcmRbMF0ubGVuZ3RoKCk7CgkJaW50IHggPSAwLCB5ID0gMDsKCQlmb3IoaW50IGkgPSAwOyBpIDwgbjsgaSsrKQoJCQlmb3IoaW50IGogPSAwOyBqIDwgbTsgaisrKQoJCQkJaWYoYm9hcmRbaV0uY2hhckF0KGopID09ICdTJykKCQkJCXsKCQkJCQl4ID0gaTsKCQkJCQl5ID0gajsKCQkJCX0KCQlmb3IoaW50IGkgPSAwOyBpIDwgbjsgaSsrKQoJCQlmb3IoaW50IGogPSAwOyBqIDwgbTsgaisrKQoJCQkJaWYoYm9hcmRbaV0uY2hhckF0KGopID09ICcjJyAmJiAoaSA9PSB4IHx8IGogPT0geSkpCgkJCQkJcmV0dXJuIC0xOwoJCXJldHVybiBuICsgbSAtIDI7Cgl9Cn0K