1. class Solution {
  2. public int numEnclaves(int[][] grid) {
  3. int n = grid.length;
  4. int m = grid[0].length;
  5.  
  6. int[][] visited = new int[n][m];
  7.  
  8. // step-1 check the boundary characters
  9. // traversing through boundary 0th col, last row, last col, 0th row
  10. for(int i=0; i<n; i++)
  11. {
  12. for(int j=0; j<m; j++)
  13. {
  14. // 0th col
  15. if(grid[i][0] == 1 && visited[i][0] != 1)
  16. {
  17. dfs(grid, visited, i, 0, n, m);
  18. }
  19. // last col
  20. else if(grid[i][m-1] == 1 && visited[i][m-1] != 1)
  21. {
  22. dfs(grid, visited, i, m-1, n, m);
  23. }
  24. // 0th row
  25. else if(grid[0][j] == 1 && visited[0][j] != 1)
  26. {
  27. dfs(grid, visited, 0, j, n, m);
  28. }
  29. // last row
  30. else if(grid[n-1][j] == 1 && visited[n-1][j] != 1)
  31. {
  32. dfs(grid, visited, n-1, j, n, m);
  33. }
  34. }
  35. }
  36.  
  37. int countLandCells = 0;
  38. for(int i=0; i<n; i++)
  39. {
  40. for(int j=0; j<m; j++)
  41. {
  42. if(grid[i][j] == 1)
  43. countLandCells++;
  44.  
  45. // reverting back as we marked 'Y' for temporary purpose
  46. else if(grid[i][j] == 2)
  47. grid[i][j] = 1;
  48. }
  49. }
  50. return countLandCells;
  51. }
  52.  
  53. int[] deltaRow = {-1, 1, 0, 0};
  54. int[] deltaCol = {0, 0, 1, -1};
  55. public void dfs(int[][] grid, int[][] visited, int row, int col, int n, int m)
  56. {
  57. visited[row][col] = 1;
  58. // Mark this cell as visited and temporary number as 2 to prevent it from being changed
  59. // as these are boundary land cells
  60. grid[row][col] = 2;
  61.  
  62. for(int i=0; i<4; i++)
  63. {
  64. int nRow = row + deltaRow[i];
  65. int nCol = col + deltaCol[i];
  66.  
  67. if(nRow >= 0 && nCol >= 0 && nRow < n && nCol < m)
  68. {
  69. // checking if neighbour cell is land cell
  70. if(visited[nRow][nCol] == 0 && grid[nRow][nCol] == 1)
  71. {
  72. dfs(grid, visited, nRow, nCol, n, m);
  73. }
  74. }
  75. }
  76. }
  77. }