[Leetcode] Word Search

来源:互联网 发布:虚拟软件 编辑:程序博客网 时间:2024/06/14 08:47

题目:

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 =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.


思路:对所有的点做DFS.


class Solution {public:    string trace;        inline bool within_border(const vector<vector<char>>& board, int row, int col) {        return row >= 0 && row < (int)board.size() && col >= 0 && col < (int)board[0].size();    }        bool dfs(const vector<vector<char>>& board, vector<vector<bool>>& visited,             int row, int col, string word) {        if (!within_border(board, row, col) || visited[row][col]) return false;        trace.push_back(board[row][col]);        visited[row][col] = true;        if (trace == word) {            trace.pop_back();            visited[row][col] = false;            return true;        } else if (trace.back() != word[trace.size()-1]) {            trace.pop_back();            visited[row][col] = false;            return false;        }        // go up        if (dfs(board, visited, row - 1, col, word)) return true;        // go down        if (dfs(board, visited, row + 1, col, word)) return true;        // go left        if (dfs(board, visited, row, col - 1, word)) return true;        // go right        if (dfs(board, visited, row, col + 1, word)) return true;        trace.pop_back();        visited[row][col] = false;        return false;    }        bool exist(vector<vector<char> > &board, string word) {        if (board.size() <= 0) return false;        vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));        for (int i = 0; i < (int)board.size(); ++i) {            for (int j = 0; j < (int)board[0].size(); ++j) {                if (dfs(board, visited, i, j, word)) return true;            }        }        return false;    }};


总结:复杂度O(n^3). 对一个点做DFS复杂度为O(m + n), 可以简化为O(n^2). 

0 0
原创粉丝点击