No need for BFS - we can use simpler DFS with recursion


#1

public class Solution {
public void solve(ArrayList<ArrayList> a) {
int h = a.size();
if (h == 0) return;
int w = a.get(0).size();
if (w == 0) return;

    // first and last column
    for (int y = 0; y < h; ++y) {
        dfs(a, 0, y);
        dfs(a, w - 1, y);
    }
    
    // first and last row
    for (int x = 0; x < w; ++x) {
        dfs(a, x, 0);
        dfs(a, x, h - 1);
    }
    
    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            if (a.get(y).get(x) == 'Y') a.get(y).set(x, 'O');
            else a.get(y).set(x, 'X');
        }
    }
}

public void dfs(ArrayList<ArrayList<Character>> a, int x, int y) {
    if (y < 0 || y >= a.size()) return;
    ArrayList<Character> row = a.get(y);
    if (x < 0 || x >= row.size()) return;
    
    if (row.get(x) == 'O') {
        row.set(x, 'Y');
        dfs(a, x - 1, y);
        dfs(a, x + 1, y);
        dfs(a, x, y - 1);
        dfs(a, x, y + 1);
    }
}

}