Advertisement
Singasking

Untitled

Jun 24th, 2023
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<vector<char>> solve(vector<vector<char>>& board) {
  4. //NXM grid
  5. int N = board.size();
  6. int M = board[0].size();
  7. vector<vector<char>> values(N,vector<char>(M,'X'));
  8. vector<vector<int>> visited(N,vector<int>(M,0));
  9. queue<pair<int,int>> q;
  10. for(int i=0;i<N;i++) {
  11. for(int j=0;j<M;j++) {
  12.  
  13. //If its a boundary O, mark all of it as unchangeable via bfs
  14. if(i==0 or j==0 or i==N-1 or j==M-1) {
  15.  
  16. if(board[i][j]=='O' && visited[i][j]==0) {
  17. //We have not processed it. add it to the queue
  18. //we run bfs
  19. visited[i][j]=1;
  20. values[i][j]='O';
  21. q.push({i,j});
  22. }
  23. }
  24. }
  25. }
  26. while(q.empty()==false) {
  27. auto temp = q.front();
  28. q.pop();
  29. int r = temp.first;
  30. int c = temp.second;
  31. vector<pair<int,int>> dirs = {{r+1,c},{r-1,c},{r,c+1},{r,c-1}};
  32. for(auto dir:dirs) {
  33. //Validation check
  34.  
  35. int rn = dir.first;
  36. int cn = dir.second;
  37.  
  38. if(rn<0 or rn>=N or cn<0 or cn>=M) { continue;}
  39.  
  40. if(board[rn][cn]=='O' && visited[rn][cn]==0) {
  41. q.push({rn,cn});
  42. visited[rn][cn]=1;
  43.  
  44. }
  45.  
  46. }
  47.  
  48. }
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55. for(int i=0;i<N;i++) {
  56. for(int j=0;j<M;j++) {
  57. if(visited[i][j]==1 && board[i][j]=='O' ) values[i][j]='O';
  58. }
  59. }
  60.  
  61. return values;
  62. }
  63. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement