LintCode : 单词搜索 II

单词搜索 II

  •  描述
  •  笔记
  •  数据
  •  评测

给出一个由小写字母组成的矩阵和一个字典。找出所有同时在字典和矩阵中出现的单词。一个单词可以从矩阵中的任意位置开始,可以向左/右/上/下四个相邻方向移动。

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出矩阵:

doaf
agai
dcan

和字典:

{"dog", "dad", "dgdg", "can", "again"}

返回 {"dog", "dad", "can", "again"}


dog:
doaf
agai
dcan

dad:

doaf
agai
dcan

can:

doaf
agai
dcan

again:

doaf
agai
dcan
挑战 
标签 

  • 先判断单个单词是否在矩阵中,若是在则加入res中
  • 判断单个单词是否在矩阵中,就是单词搜索那道题了http://blog.csdn.net/cumt_cx/article/details/48277395?locationNum=1&fps=1
          递归回溯,用一个visited记录走过的路,不能走成功就回溯。
        用一个direct2维数组表示其4个方位可访问的位置
public class Solution {
    /**
     * @param board: A list of lists of character
     * @param words: A list of string
     * @return: A list of string
     */
    public ArrayList wordSearchII(char[][] board, ArrayList words) {
        // write your code here
    	if(board==null||board.length==0){
    		return null;
    	}
    	ArrayList res = new ArrayList();
    	if(words.isEmpty()||words.size()==0){
    		return res;
    	}
    	for(String word:words){
    		if(exist(board, word)){
    			res.add(word);
    		}
    	}
    	return res;
    }

	public boolean exist(char[][] board, String word) {
		// write your code here
		if (null == board || 0 == board.length) {
			return false;
		}
		boolean visited[][] = new boolean[board.length][board[0].length];
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[0].length; j++) {
				if (board[i][j] == word.charAt(0)) {
					visited[i][j] = true;
					if (word.length() == 1 || search(i, j, board, word.substring(1), visited)) {
						return true;
					}
					visited[i][j] = false;
				}
			}
		}
		return false;
	}

	public boolean search(int i, int j, char[][] board, String word, boolean[][] visited) {
		if (word.length() == 0) {
			return true;
		}
		int[][] direct = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
		for (int k = 0; k < direct.length; k++) {
			int ii = i + direct[k][0];
			int jj = j + direct[k][1];
			if (ii >= 0 && ii < board.length && jj >= 0 && jj < board[i].length && !visited[ii][jj]
					&& word.charAt(0) == board[ii][jj]) {
				visited[ii][jj] = true;
				if (word.length() == 1 || search(ii, jj, board, word.substring(1), visited)) {
					return true;
				}
				visited[ii][jj] = false;
			}
		}
		return false;
	}
}


你可能感兴趣的:(LintCode : 单词搜索 II)