-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_23.java
More file actions
96 lines (92 loc) · 2.81 KB
/
Copy pathDay_23.java
File metadata and controls
96 lines (92 loc) · 2.81 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Number of Distinct Islands
class Solution {
public void dfs(int r,int c,char[][] grid,List<List<Integer>> ans,int pr,int pc){
int n = grid.length;
int m = grid[0].length;
grid[r][c] = 'W';
ans.add(Arrays.asList(r-pr,c-pc));
int[] delrow = {-1,0,1,0};
int[] delcol = {0,1,0,-1};
for(int i=0;i<4;i++){
int nr = r + delrow[i];
int nc = c + delcol[i];
if(nr>=0 && nr<n && nc>=0 && nc<m && grid[nr][nc] == 'L'){
dfs(nr,nc,grid,ans,pr,pc);
}
}
}
public int countDistinctIslands(char[][] grid) {
int n = grid.length;
int m = grid[0].length;
Set<List<List<Integer>>> st = new HashSet<>();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j] == 'L'){
List<List<Integer>> ans = new ArrayList<>();
dfs(i,j,grid,ans,i,j);
st.add(ans);
}
}
}
return st.size();
}
}
// Detect Cycles in 2D Grid
class Solution {
public boolean dfs(int r,int c,char[][] grid,boolean[][] vis,int pr,int pc) {
int n = grid.length;
int m = grid[0].length;
vis[r][c] = true;
char val = grid[r][c];
int[] delrow = {-1,0,1,0};
int[] delcol = {0,1,0,-1};
for(int i=0;i<4;i++){
int nr = r + delrow[i];
int nc = c + delcol[i];
if(nr>=0 && nr<n && nc>=0 && nc<m && grid[nr][nc] == val && !vis[nr][nc]){
if(dfs(nr,nc,grid,vis,r,c)) return true;
}
else if(nr>=0 && nr<n && nc>=0 && nc<m && vis[nr][nc] && grid[nr][nc] == val && (pr != -1 && pc != -1) && (pr != nr || pc != nc)){
return true;
}
}
return false;
}
public boolean containsCycle(char[][] grid) {
int n = grid.length;
int m = grid[0].length;
boolean[][] vis = new boolean[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!vis[i][j]){
if(dfs(i,j,grid,vis,-1,-1)) return true;
}
}
}
return false;
}
}
// Longest Consecutive Sequence
class Solution {
public int longestConsecutive(int[] nums) {
int n = nums.length;
Set<Integer> st = new HashSet<>();
for(int i=0;i<n;i++){
st.add(nums[i]);
}
int maxcnt = 0;
for(var it : st){
int cnt = 1;
if(st.contains(it-1)) continue;
else {
int x = it;
while(st.contains(x+1)){
x++;
cnt++;
}
maxcnt = Math.max(cnt,maxcnt);
}
}
return maxcnt;
}
}