字典找单词路径的更新版

题目在leetcode上和白书(18-10)上都出现过,不再赘述。为什么还要再拿出来写一遍?

以前做leetcode的解法只要求返回总共需要的步数,最近看了白书,发现只要在里面加入一个backtracking的map结构,就可以返回单词变化路径的list。


Java解法如下:

class Test{
    public static void main(String[] args){
		Test test = new Test();
		HashSet<String> dic = new HashSet<String>();
		dic.add("bug");
		dic.add("cog");
		dic.add("cag");
		dic.add("dog");
		dic.add("bed");
		dic.add("deg");
		dic.add("beg");
		dic.add("kug");
		dic.add("kog");
		String start = "bug", end = "kog";
		
		ArrayList<String> res = test.bfs(dic, start, end);
		if(res != null)
			for(int i=0; i<res.size(); i++)
				System.out.println(res.get(i));
		else System.out.println("null");
	}
	
	public ArrayList<String> bfs(HashSet<String> dic, String start, String end){
		Queue<String> q = new LinkedList<String>();
		HashSet<String> visited = new HashSet<String>();
		HashMap<String, String> backtrack = new HashMap<String, String>();
		int steps = 0;
		
		q.add(start);
		visited.add(start);
		int size = 1, cnt = 0;
		
		while(!q.isEmpty()){
			String cur = q.poll();
			cnt++;
			if(cur.equals(end)){
				System.out.println("steps is : " + steps);
				ArrayList<String> res = new ArrayList<String>();
				while(end != null){
					res.add(0, end);
					end = backtrack.get(end);
				}
				return res;
			}
			for(String str : getNextLevel(cur, dic, visited)){
				q.add(str);
				backtrack.put(str, cur);
			}
			if(cnt == size){
				steps++;
				size = q.size();
				cnt = 0;
			}
		}
		return null;
	}
	
	public HashSet<String> getNextLevel(String cur, HashSet<String> dic, HashSet<String> visited){
		HashSet<String> res = new HashSet<String>();
		for(int i=0; i<cur.length(); i++){
			char[] chs = cur.toCharArray();
			for(char c='a'; c<='z'; c++){
				chs[i] = c;
				String tmp = new String(chs);
				if(dic.contains(tmp) && !visited.contains(tmp)){
					visited.add(tmp);
					res.add(tmp);
				}
			}
		}
		return res;
	}
}

小结:

backtracking的map相当精髓,见识了新用法,赞。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值