单词搜索

问题

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

 

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

 

思路

这道题和小岛的那道题很像

 代码

public class Test1 {
    public static void main(String[] args) {
        //char[][] board ={
  {'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
        char[][] board ={
  {'A','A'}};
        System.out.println(exist(board,"AAA"));
    }
    public static boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || word == null) {
            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 (dfs(board, word, 0, i, j, visited))
                {
                    return true;
                }
            }
        }
        return false;
    }

    private static boolean dfs(char[][] board, String word, int index, int i, int j, boolean[][] visited) {
        if (index == word.length())
        {
            return true;
        }
        int m = board.length, n = board[0].length;
        if (i < 0 || j < 0 || i >= m || j >= n || visited[i][j] || board[i][j] != word.charAt(index))
        {
            return false;
        }
        visited[i][j] = true;
        boolean res = dfs(board, word, index+1, i-1, j, visited) ||
                dfs(board, word, index+1, i+1, j, visited) ||
                dfs(board, word, index+1, i, j+1, visited) ||
                dfs(board, word, index+1, i, j-1, visited);

        visited[i][j] = false;
        return res;
    }
}