字符串接龙
经过上面的练习,大家可能会感觉 广搜不过如此,都刷出自信了,本题让大家初步感受一下,广搜难不在广搜本身,而是如何应用广搜。
import java.util.*;
class Main{
public static void main (String[] args) {
/* code */
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
String beginStr = sc.next();
String endStr = sc.next();
HashSet<String> strList = new HashSet<>();
for(int i = 0; i<n; i++){
strList.add(sc.next());
}
int res = bfs(beginStr,endStr,strList);
System.out.println(res);
}
public static int bfs(String beginStr,String endStr, HashSet<String> strList){
Queue<String> que = new LinkedList<String>();
HashMap<String,Integer> path = new HashMap<>();
que.offer(beginStr);
path.put(beginStr,1);
int count = 1;
while(que.isEmpty() == false){
String curword = que.poll();
count = path.get(curword);
char[] ch = curword.toCharArray();
for(int i = 0; i<ch.length; i++){
ch = curword.toCharArray();
for(char inplace = 'a'; inplace <= 'z'; inplace++){
ch[i] = inplace;
//String newWord = ch.toString();
//toString得到的是地址值
String newWord = new String(ch);
if(newWord.equals(endStr)){
return count + 1;
}
if(strList.contains(newWord)){
path.put(newWord,count + 1);
que.offer(newWord);
strList.remove(newWord);
}
}
}
}
return 0;
}
}
有向图的完全可达性
深搜有细节,同样是深搜两种写法的区别,以及什么时候需要回溯操作呢?
import java.util.*;
public class Main{
static List<List<Integer>> edgeList = new LinkedList<>();
public static void main (String[] args) {
/* code */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
for(int i = 0; i <= n; i++){
edgeList.add(new LinkedList<Integer>());
}
//构建边的集合
for(int i = 0; i < k; i++){
int s = sc.nextInt();
int t = sc.nextInt();
edgeList.get(s).add(t);
}
boolean[] visited = new boolean[n+1];
dfs(visited,1);
int res = 1;
for(int i = 1; i<=n;i++){
if(!visited[i]){
res = -1;
break;
}
}
System.out.println(res);
}
public static void dfs(boolean[] visited, int curNode){
if(visited[curNode]){return;}
visited[curNode] = true;
List<Integer> curEdge =edgeList.get(curNode);
for(int x : curEdge){
dfs(visited,x);
}
}
}
岛屿的周长
简单题,避免大家惯性思维,建议大家先独立做题。
import java.util.*;
class Main{
static int[][] dirs = {{1,0},{0,1},{-1,0},{0,-1}};
static int count = 0;
public static void main (String[] args) {
/* code */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i< n;i++){
for(int j = 0; j< m; j++){
grid[i][j] = sc.nextInt();
}
}
for(int i = 0; i< n;i++){
for(int j = 0; j< m; j++){
if(grid[i][j] ==1){
staLength(grid, i, j);
}
}
}
System.out.println(count);
}
static void staLength(int[][] grid, int x, int y){
for(int[] dir : dirs){
int nextX = x + dir[0];
int nextY = y + dir[1];
if(nextX <0 || nextX >= grid.length || nextY<0 || nextY>=grid[0].length || grid[nextX][nextY] ==0){
count++;
}
}
}
}