79. Word Search

来源:互联网 发布:淘宝卖lol限定皮肤 编辑:程序博客网 时间:2024/06/04 19:40

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.

For example,
Given board =

[  ['A','B','C','E'],  ['S','F','C','S'],  ['A','D','E','E']]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

查找字符串,字符相邻,本类型的题目均可通过dfs求解,程序如下所示:

class Solution {    public boolean dfs(char[][] board, boolean[][] isVisited, int len, String word, int i, int row, int j, int col){        if (len==word.length()){            return true;        }        if (i < 0||j < 0||i >= row || j >= col){            return false;        }        if (board[i][j] != word.charAt(len)){            return false;        }        if (isVisited[i][j] == false) {            isVisited[i][j] = true;            if(dfs(board, isVisited, len+1, word, i + 1, row, j, col)||            dfs(board, isVisited, len+1, word, i - 1, row, j, col)||            dfs(board, isVisited, len+1, word, i, row, j + 1, col)||            dfs(board, isVisited, len+1, word, i, row, j - 1, col)){                return true;            }            isVisited[i][j] = false;        }        return false;    }    public boolean exist(char[][] board, String word) {        if (board.length == 0){            return false;        }        int row = board.length, col = board[0].length;        for (int i = 0; i < row; ++ i){            for (int j = 0; j < col; ++ j){                if (board[i][j] == word.charAt(0)){                    boolean[][] isVisited = new boolean[row][col];                    if (dfs(board, isVisited, 0, word, i, row, j, col)){                        return true;                    }                }            }        }        return false;    }}