#123 Word Search

来源:互联网 发布:雅虎股票数据接口 编辑:程序博客网 时间:2024/05/17 23:23

题目描述:

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 + backtracking题。首先遍历board,选取与word[0]相同的element。对于每一个这样的element,check它的上下左右,看能不能找到一个string == word.substr(1),以此类推。recursion 函数中,判断true的条件是是否check完最后一个char in word;判断false的条件是,坐标超出范围,或者board坐标所在的element != word[index].

My code (AC = 30ms):

class Solution {public:    /**     * @param board: A list of lists of character     * @param word: A string     * @return: A boolean     */         bool exist(vector<vector<char> > &board, string word) {        // write your code here        // if word is empty        if (word == "") return true;                // if board is empty        int row = board.size();        if (row == 0) {            return false;        }                int col = board[0].size();        if (col == 0) {            return false;        }                // check if the word exists in board        for (int i = 0; i < row; i++) {            for (int j = 0; j < col; j++) {                if (board[i][j] == word[0]) {                    if (existHelper(board, 0, word, i, j)) return true;                }            }        }                return false;    }        bool existHelper(vector<vector<char> > &board,                     int index,                     string word,                     int x,                     int y)     {        // condition of found        if (index == word.length()) {            return true;        }                // directly return false if condition is follows        if (x < 0 || x >= board.size() ||            y < 0 || y >= board[0].size() ||            board[x][y] != word[index])         {            return false;        }                // check the elements in 4 directions        int dx[4] = {1, 0, -1, 0};        int dy[4] = {0, 1, 0, -1};        board[x][y] = '*';        for (int i = 0; i < 4; i++) {            int mx = dx[i] + x;            int my = dy[i] + y;                        if(existHelper(board, index + 1, word, mx, my)) return true;        }        board[x][y] = word[index];                return false;    }};

0 0
原创粉丝点击