[US Giants] 八. Search & Recurison

Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Given board =

[
  "ABCE",
  "SFCS",
  "ADEE"
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

思路:遍历找到单词的第一个字母,然后开始四个方向上dfs。但是这题有一点要注意就是题没有要求每一个字母cell只能用一次,因此要将当前这串里访问过的字母用'#'表示,当整个dfs完再将mark为'#'的字母复原。

复原字母的原因是例如'CCB',在找到C为第一个字母开始遍历以后,经过递归发现没有合适的结果,复原这里面标记过的字母,返回false,然后再遍历后面的字母,直到遇到C,以C为第一个字母开始遍历,因为这个C会在向上走的时候取到C,所以如果之前不复原,这时候这个C的位置是'#',导致结果错误。

public class Solution {
    public boolean exist(char[][] board, String word) {
        if(board==null || board.length==0){
            return false;
        }  
        if(word.length()==0){
            return true;
        }        
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                if(board[i][j]==word.charAt(0)){ 
                    if(find(board,i,j,word,0)){
                        return true;
                    }
                }
            }
        }
        return false;        
    }
    
    private boolean find(char[][] board,int i,int j,String word,int pos){
        if(pos==word.length()){
           return true; 
        }
        if(!isValid(board,i,j,word) || board[i][j]!=word.charAt(pos)){
            return false;
        }
               
        board[i][j]='#';
        boolean result=find(board,i-1,j,word,pos+1)
                     ||find(board,i+1,j,word,pos+1)
                     ||find(board,i,j-1,word,pos+1)
                     ||find(board,i,j+1,word,pos+1);
        board[i][j]=word.charAt(pos);
        return result;      
    } 
    
    
    private boolean isValid(char[][] board,int x,int y,String word){
        if(x<0 || x>=board.length){
            return false;
        }
        if(y<0 || y>=board[0].length){
            return false;
        }
        return true;
    }
}
Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
Example

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

public class Solution {
    /**
      * @param start, a string
      * @param end, a string
      * @param dict, a set of string
      * @return an integer
      */
    public int ladderLength(String start, String end, Set<String> dict) {
        if(dict==null || dict.size()==0){
            return 0;
        }
        if(start.equals(end)){
            return 1;
        }
        dict.add(start);
        dict.add(end);
        
        Queue<String> queue=new LinkedList<>();
        Set<String> set=new HashSet<>();
        
        queue.offer(start);
        set.add(start);
        
        int length=1;
        while(!queue.isEmpty()){
            length++;                           //由题目的例子知,算上start和end,虽然结果是5,但中间转换4次
            int size=queue.size();              //只要queue不为空,就length++,如果当前的就是end,返回此时的length
            for(int i=0;i<size;i++){
                String cur=queue.poll();        //对于当前的cur,拿到dict里相应的变形词list
                for(String nextWord:getNextWords(cur,dict)){  
                    if(set.contains(nextWord)){ //要找最短路径,一定是这个词用过就不会再用了
                        continue;               //因为如果有第二次用,干嘛不直接用第一次时候的结果
                    }
                    if(nextWord.equals(end)){
                        return length;
                    }
                    queue.offer(nextWord);
                    set.add(nextWord);
                }
            }
        }
        return length;
    }
                                               //找到word在dict里存在的每一个变形词,并且只能一个字符改变
    private ArrayList<String> getNextWords(String word,Set<String> dict){
        ArrayList<String> list=new ArrayList<>();
        for(char c='a';c<='z';c++){
            for(int i=0;i<word.length();i++){
                if(c==word.charAt(i)){
                    continue;
                }
                String nextWord=replaceWord(word,i,c);
                if(dict.contains(nextWord)){
                    list.add(nextWord);
                }
            }
        }
        return list;
    } 
    
    private String replaceWord(String word,int i,char c){
        char[] chars=word.toCharArray();
        chars[i]=c;
        return new String(chars);
    }
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值