kk
This commit is contained in:
39
src/main/java/com/dota/graph/_2316/Solution.java
Normal file
39
src/main/java/com/dota/graph/_2316/Solution.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package com.dota.graph._2316;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
class Solution {
|
||||
public long countPairs(int n, int[][] edges) {
|
||||
List<Integer>[] g = new ArrayList[n];
|
||||
Arrays.setAll(g, i -> new ArrayList<>());
|
||||
for (int[] edge : edges) {
|
||||
g[edge[0]].add(edge[1]);
|
||||
g[edge[1]].add(edge[0]);
|
||||
}
|
||||
|
||||
var vis = new boolean[n];
|
||||
long res = 0;
|
||||
int sum = 0;
|
||||
for (int i = 0; i < g.length; i++) {
|
||||
if (!vis[i]) {
|
||||
int size = dfs(i, vis, g);
|
||||
res += (long)size * sum;
|
||||
sum += size;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
int dfs(int i, boolean[] visited, List<Integer>[] arr) {
|
||||
visited[i] = true;
|
||||
int size = 1;
|
||||
for (Integer integer : arr[i]) {
|
||||
if (!visited[integer]) {
|
||||
size += dfs(integer, visited, arr);
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
}
|
37
src/main/java/com/dota/gridGraph/_1559/Solution.java
Normal file
37
src/main/java/com/dota/gridGraph/_1559/Solution.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.dota.gridGraph._1559;
|
||||
|
||||
class Solution {
|
||||
public boolean containsCycle(char[][] grid) {
|
||||
int n = grid.length;
|
||||
int m = grid[0].length;
|
||||
var book = new int[n][m];
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < m; j++) {
|
||||
if (book[i][j] == 0) {
|
||||
var res = df(i, j, i, j, grid[i][j], book, 0, grid);
|
||||
if (res) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean df(int i, int j, int x, int y, char c, int[][] book, int step, char[][] chars) {
|
||||
if (i < 0 || j < 0 || i >= book.length || j >= book[i].length || c != chars[i][j]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (book[i][j] == 0) {
|
||||
step++;
|
||||
book[i][j] = step;
|
||||
return df(i + 1, j, i, j, c, book, step, chars) ||
|
||||
df(i - 1, j, i, j, c, book, step, chars) ||
|
||||
df(i, j + 1, i, j, c, book, step, chars) ||
|
||||
df(i, j - 1, i, j, c, book, step, chars);
|
||||
}
|
||||
|
||||
return book[x][y] - book[i][j] > 2;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user