单词搜索

package algorithms;

import java.util.Arrays;

public class Exp3_2 {
    private int pathLength;
    private int rows;
    private int cols;
    private boolean[][] visited;
    char[] wordArray;

    public boolean exist(char[][] board, String word) {
        if (board == null)
            return false;

        rows = board.length;
        cols = board[0].length;
        // 记录该元素是否已经被访问过了
        visited = new boolean[rows][cols];
        for(int i=0;i<rows;i++)
            Arrays.fill(visited[i], false);
        wordArray = word.toCharArray();
        pathLength = 0;

        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++) {
                if (findPath(board, i, j)) {
                    return true;
                }
            }
        return false;
    }

    private boolean findPath(char[][] board, int i, int j) {
        boolean flag = false;
        if (pathLength == wordArray.length)
            return true;
        if (i >= 0 && i < rows && j >= 0 && j < cols && board[i][j] == wordArray[pathLength]
                && visited[i][j] == false) {
            pathLength++;
            visited[i][j] = true;
            flag = findPath(board, i+1, j) || findPath(board, i-1, j) || findPath(board, i, j+1)
                    || findPath(board, i, j-1);
            if (!flag) {
                pathLength--;
                visited[i][j] = false;
            }
        }
        return flag;
    }
    
    public static void main(String[] args) {
        char[][] board= {{'a','b','c','e'},{'s','f','c','s'},{'a','d','e','e'}};
        String word = "abcced";
        boolean b = new Exp3_2().exist(board, word);
        System.out.println(b);
    }
}

 

posted @ 2019-04-11 15:29  Practical  阅读(246)  评论(0编辑  收藏  举报