Advertisement
unknown_0711

Untitled

Dec 29th, 2022
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1.  
  2. // User function Template for Java
  3. class Solution {
  4.  
  5. // 2D array for the storing the horizontal and vertical
  6. // directions. (Up, left, down, right}
  7. int R[] = {0, 0, 1, -1};
  8. int C[] = {1, -1, 0, 0};
  9. int D[] = {1, 2, 3, 4};
  10.  
  11. // Function to perform bfs of the input grid
  12. String layout(int i, int j, int grid[][]) {
  13. StringBuilder sb = new StringBuilder();
  14. Queue<int[]> queue = new LinkedList<>();
  15. int size, current[], nR, nC;
  16. queue.add(new int[]{i, j});
  17. while (!queue.isEmpty()) {
  18. size = queue.size();
  19. while (size != 0) {
  20. size--;
  21. current = queue.poll();
  22. for (int k = 0; k < R.length; k++) {
  23. nR = current[0] + R[k];
  24. nC = current[1] + C[k];
  25. if (nR < 0 || nR == grid.length || nC < 0 ||
  26. nC == grid[0].length || grid[nR][nC] != 1) {
  27. sb.append(0);
  28. continue;
  29. }
  30. if (grid[nR][nC] == 1) {
  31. queue.add(new int[]{nR, nC});
  32. grid[nR][nC] = 2;
  33. sb.append(D[k]);
  34. }
  35. }
  36. }
  37. }
  38. return sb.toString();
  39. }
  40.  
  41. int countDistinctIslands(int[][] grid) {
  42. Set<String> distinct = new HashSet<>();
  43. for (int i = 0; i < grid.length; i++) {
  44. for (int j = 0; j < grid[0].length; j++) {
  45. if (grid[i][j] == 1) {
  46. distinct.add(layout(i, j, grid));
  47. }
  48. }
  49. }
  50. return distinct.size();
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement