字符串接龙
经过上面的练习,大家可能会感觉 广搜不过如此,都刷出自信了,本题让大家初步感受一下,广搜难不在广搜本身,而是如何应用广搜。
有向图的完全可达性
深搜有细节,同样是深搜两种写法的区别,以及什么时候需要回溯操作呢?
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
Vector<Vector<Integer>> graph = new Vector<>(n + 1);
for (int i = 0; i <= n; i++) {
graph.add(new Vector<>());
}
while (m-- > 0) {
int s = scanner.nextInt();
int t = scanner.nextInt();
graph.get(s).add(t);
}
boolean[] visited = new boolean[n + 1];
visited[1] = true;
dfs(graph, 1, visited);
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
System.out.println(-1);
return;
}
}
System.out.println(1);
}
private static void dfs(Vector<Vector<Integer>> graph, int key, boolean[] visited) {
Vector<Integer> keys = graph.get(key);
for (int nextKey : keys) {
if (!visited[nextKey]) {
visited[nextKey] = true;
dfs(graph, nextKey, visited);
}
}
}
}
-
岛屿的周长
简单题,避免大家惯性思维,建议大家先独立做题。
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
Vector<Vector<Integer>> grid = new Vector<>(n);
for (int i = 0; i < n; i++) {
grid.add(new Vector<Integer>(m));
for (int j = 0; j < m; j++) {
grid.get(i).add(scanner.nextInt());
}
}
int[][] direction = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid.get(i).get(j) == 1) {
for (int k = 0; k < 4; k++) {
int x = i + direction[k][0];
int y = j + direction[k][1];
if (x < 0 || x >= n || y < 0 || y >= m || grid.get(x).get(y) == 0) {
result++;
}
}
}
}
}
System.out.println(result);
}
}