110.字符串接龙
经过上面的练习,大家可能会感觉 广搜不过如此,都刷出自信了,本题让大家初步感受一下,广搜难不在广搜本身,而是如何应用广搜。
代码随想录
import java.util.*;public class Main{public static void main (String[] args) {Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();scanner.nextLine();String str = scanner.nextLine();String[] strs = str.trim().split(" ");String beginStr = strs[0];String endStr = strs[1];List<String> wordlist = new ArrayList<>();for(int i = 0; i < n; i++){wordlist.add(scanner.nextLine());}System.out.println(bfs(wordlist, beginStr, endStr));}public static int bfs(List<String> wordlist, String beginStr, String endStr){Deque<String> deque = new ArrayDeque<>();//存放访问过的元素,以及距离Map<String, Integer> visitMap = new HashMap<>();deque.add(beginStr);visitMap.put(beginStr, 1);while(!deque.isEmpty()){String curString = deque.remove();int path = visitMap.get(curString);int len = curString.length();for(int i = 0; i < len; i++){char[] chararr = curString.toCharArray();for(char temp = 'a'; temp <