SalmaYasser

Untitled

Jan 17th, 2020
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. class Solution {
  2. public:
  3. bool not_valid (vector<vector<char>>& board, int i , int j)
  4. {
  5. return i < 0 || i >= board.size() || j < 0 || j >= board[0].size();
  6. }
  7. void dfs (vector<vector<char>>& board, int i , int j)
  8. {
  9. if (not_valid ( board,i, j ) || board [i][j] == '.')
  10. return;
  11. board [i][j] = '.';
  12.  
  13. dfs (board,i + 1 , j);
  14. dfs (board,i - 1 , j);
  15. dfs (board,i, j + 1);
  16. dfs (board,i , j - 1);
  17.  
  18.  
  19. }
  20. int countBattleships(vector<vector<char>>& board) {
  21.  
  22. int res = 0;
  23.  
  24. for (int i = 0 ; i < board.size(); i++)
  25. {
  26. for (int j = 0 ; j < board[0].size(); j++)
  27. {
  28. if (board[i][j] == 'X')
  29. {
  30. res++;
  31. dfs (board,i, j);
  32. }
  33. }
  34. }
  35.  
  36. return res;
  37. }
  38. };
  39.  
  40.  
  41.  
  42. only look for the first one
  43.  
  44. int countBattleships(vector<vector<char>>& board) {
  45.  
  46. int res = 0 ;
  47. int szi = board.size();
  48. int szj = board[0].size();
  49.  
  50. for ( int i = 0 ; i < szi ; i++)
  51. {
  52. for (int j = 0 ; j < szj ; j ++)
  53. {
  54. if (board[i][j]=='X')
  55. {
  56. if ( (i == 0 || board[i-1][j]=='.') && (j==0 || board[i][j-1]=='.'))
  57. res++;
  58. }
  59.  
  60. }
  61. }
  62. return res;
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment