1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { void bfs(vector<vector<char>>& mat, int sy, int sx, int n, int m) { int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1}; queue<pair<int,int>> q; q.push({sy,sx}); mat[sy][sx] = '#'; while(!q.empty()) { auto p = q.front(); q.pop(); auto y = p.first, x = p.second; for(int i = 0; i < 4; i++) { int ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < n and 0 <= nx and nx < m and mat[ny][nx] == 'O') { mat[ny][nx] = '#'; q.push({ny,nx}); } } } } public: vector<vector<char>> fill(int n, int m, vector<vector<char>> mat) { for(int i = 0; i < n; i++) { if(mat[i][0] == 'O') bfs(mat,i,0,n,m); if(mat[i][m-1] == 'O') bfs(mat,i,m-1,n,m); } for(int j = 0; j < m; j++) { if(mat[0][j] == 'O') bfs(mat,0,j,n,m); if(mat[n-1][j] == 'O') bfs(mat,n-1,j,n,m); } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(mat[i][j] == 'O') mat[i][j] = 'X'; else if(mat[i][j] == '#') mat[i][j] = 'O'; } } return mat; } };
|