1. 程式人生 > >[LeetCode]Freedom Trail

[LeetCode]Freedom Trail

In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring", and use the dial to spell a specific keyword in order to open the door.

Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum

 number of steps in order to spell all the characters in the keyword.

Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button. 

At the stage of rotating the ring to spell the key character key[i]:
  1. You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring'scharacters at the 12:00 direction, where this character must equal to the character key[i]
    .
  2. If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.

老生常談的做法 ,普通dfs會超時,記憶化dfs或則dp解題

普通dfs超時程式碼:

public class Solution {
	  //普通dfs  會超時
	  public int findRotateSteps(String ring, String key) {
		  int len=ring.length();
		  HashMap<Character,HashSet<Integer>> map=new HashMap<Character, HashSet<Integer>>();
		  for(int i=0;i<ring.length();i++){
			  if(!map.containsKey(ring.charAt(i))){
				  map.put(ring.charAt(i),new HashSet<Integer>());
			  }
			  map.get(ring.charAt(i)).add(i);
		  }
		  dfs(0,key,map,len,0);
		  return re==Integer.MAX_VALUE?-1:re+key.length();
	  }
	  int trace=0;
	  int re=Integer.MAX_VALUE;
	  public void dfs(int k,String key,HashMap<Character,HashSet<Integer>> map,int len,int pos){
		  if(k==key.length()){
			  re=Math.min(trace, re);
			  return;
		  }
		  HashSet<Integer> level=map.get(key.charAt(k));
		  for(Integer num:level){
			  int dis=Math.min(Math.abs(num-pos), len-Math.abs(num-pos));//這裡不是Math.abs(len-num+pos)
			  trace+=dis;
			  dfs(k+1,key,map,len,num);
			  trace-=dis;
			  
		  }
	  }
	  public static void main(String[] args) {
		  String ring="caotmcaataijjx";
		  String key="oatjiioicitatajtijciocjcaaxaaatmctxamacaamjjx";
		  Solution s=new Solution();
		  System.out.println(s.findRotateSteps(ring, key));
	}
}

記憶化dfs程式碼:
public class Solution2 {
	//一些分析:
	// 對於dfs而言  它永遠是對圖的搜尋(決策樹也是圖) 圖的每一個頂點也就是每一個狀態 
	//本題所用的dp寫法是自上而下的  其實自下而上是和dfs的邏輯更相符合的  即從ring.length-1向前dp 
	//但是由於本題  從上而下和從下而上是一模一樣的 所以沒有必要糾結於dp的寫法 
	//在記憶化dfs的程式碼中 dp[][] 表示從(i,j)位置到最終路徑的最小距離
	//而在dp寫法中  dp[][] 則表示從(0,0)到(i,j)的距離
	  public int findRotateSteps(String ring, String key) {
		  int len=ring.length();
		  HashMap<Character,HashSet<Integer>> map=new HashMap<Character, HashSet<Integer>>();
		  dp=new int[key.length()][ring.length()];
		  for(int i=0;i<dp.length;i++) Arrays.fill(dp[i],Integer.MAX_VALUE);
		  for(int i=0;i<ring.length();i++){
			  if(!map.containsKey(ring.charAt(i))){
				  map.put(ring.charAt(i),new HashSet<Integer>());
			  }
			  map.get(ring.charAt(i)).add(i);
		  }
	  	  int re=dfs(0,key,map,len,0);
		  return re==Integer.MAX_VALUE?-1:re+key.length();
	  }
	  int[][] dp;
	  public int dfs(int k,String key,HashMap<Character,HashSet<Integer>> map,int len,int pos){
		  if(k==key.length()){
			  return 0;
		  }
		  if(dp[k][pos]!=Integer.MAX_VALUE) return dp[k][pos];
		  HashSet<Integer> level=map.get(key.charAt(k));
		  for(Integer num:level){
			  int dis=Math.min(Math.abs(num-pos), len-Math.abs(num-pos));//這裡不是Math.abs(len-num+pos)
			  int re=dfs(k+1,key,map,len,num);
			  dp[k][pos]=Math.min(re+dis, dp[k][pos]);
		  }
		  return dp[k][pos];
	  }
}
dp程式碼:
public class Solution3 {
	public int findRotateSteps(String ring, String key) {
		int[][] dp=new int[key.length()][ring.length()];
		for(int i=0;i<dp.length;i++){
			Arrays.fill(dp[i],Integer.MAX_VALUE);
		}
		for(int i=0;i<dp.length;i++){
			for(int j=0;j<dp[0].length;j++){
				if(ring.charAt(j)==key.charAt(i)){
					for(int k=0;k<dp[0].length;k++){
						if(i==0)
							dp[i][j]=Math.min(j, ring.length()-j);
						else{
							if(ring.charAt(k)==key.charAt(i-1))
								dp[i][j]=Math.min(dp[i][j],dp[i-1][k]+Math.min(Math.abs(j-k),ring.length()-Math.abs(j-k)));
						}
					}
				}
			}
		}
		int re=Integer.MAX_VALUE;
		for(int i=0;i<dp[0].length;i++){
			re=Math.min(re,dp[dp.length-1][i]);
		}
		return re==Integer.MAX_VALUE?-1:re+key.length();
	}
}