*[Lintcode]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.

Example

Given board =

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

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

分析:实现题。双重循环+DFS。以board中每一个字符为起点,查看是否可以找到目标字符串。

public class Solution {
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    public boolean exist(char[][] board, String word) {
        if(word == null || word.length() == 0) return true;
        if(board.length == 0 || board[0].length == 0) return false;
        boolean[][] visit = 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(helper(board, visit, i, j, 0, word)) return true;  
            }
        }
        return false;
    }
    
    boolean helper(char[][] board, boolean[][] visit, int row, int col, int index, String str) {
        if(index >= str.length()) {
            return true;
        }
        
        if(row < 0 || col < 0 || row >= board.length || col >= board[0].length) {
            return false;
        }
        
        if(!visit[row][col] && str.charAt(index) == board[row][col]) {
            visit[row][col] = true;//<-
            boolean res = helper(board, visit, row + 1, col, index + 1, str) || 
                helper(board, visit, row - 1, col, index + 1, str) ||
                helper(board, visit, row, col + 1, index + 1, str) ||
                helper(board, visit, row, col - 1, index + 1, str);
            visit[row][col] = false;//<-
            return res;
        }
        
        return false;
    }
}



你可能感兴趣的:(算法)