[leetcode] 79. Word Search

来源:互联网 发布:清北学霸 知乎 编辑:程序博客网 时间:2024/06/08 08:51

Question:

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.

Solution:

简单递归,用DFS的思想,在一开始找到一个与word[0]相同的字母,开始递归,从那个位置开始,向四周找寻是否有与word[1]相同的字母,找到则继续递归,否则就返回继续找上一级是否有相同的字母,如此类推。成功的条件是当前搜寻的层数比word的字母个数还深则说明搜索完。

做完后点开看别人的代码,发现大佬们都不用visited数组记录访问过的位置,直接在访问过的位置打标记即可,反正一层递归完visited都要重置的,为什么当初就想不到这么好的方法呢。。。

class Solution {public:    bool exist(vector<vector<char>>& board, string word) {        vector<vector<bool>> visited;        for (int i = 0; i < board.size(); i++) {            vector<bool> tmp(board[i].size(), false);            visited.push_back(tmp);        }        for (int i = 0; i < board.size(); i++) {            for (int j = 0; j < board[0].size(); j++) {                if (board[i][j] == word[0] && helper(board, visited, i, j, 1, word)) {                    return true;                }            }        }        return false;    }    bool helper(vector<vector<char>>& board, vector<vector<bool>>& visited, int row, int col, int pos, string& word) {        if (pos == word.size())            return true;        visited[row][col] = true;        if (row > 0 && board[row-1][col] == word[pos] && !visited[row-1][col] && helper(board, visited, row-1, col, pos+1, word)) {            return true;        } else if (col > 0 && board[row][col-1] == word[pos] && !visited[row][col-1] && helper(board, visited, row, col-1, pos+1, word)) {            return true;        } else if (row < board.size()-1 && board[row+1][col] == word[pos] && !visited[row+1][col] && helper(board, visited, row+1, col, pos+1, word)) {            return true;        } else if (col < board[row].size()-1 && board[row][col+1] == word[pos] && !visited[row][col+1] && helper(board, visited, row, col+1, pos+1, word)) {            return true;        }        visited[row][col] = false;        return false;    }};
原创粉丝点击