LeetCode

来源:互联网 发布:温度数据采集板 编辑:程序博客网 时间:2024/04/19 20:42

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.


在一个board是否能找到某个单词,单词中相邻字母需要在格子中相邻(用过的字母不可再用)。

一个dfs,时间复杂度O(nm),空间复杂度O(nm)

class Solution {private:    int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};public:    bool exist(vector<vector<char>>& board, string word) {        if (word.size() == 0) return true;        if (!board.size() || !board[0].size()) return false;        int n = board.size(), m = board[0].size();        bool ans = false;        vector<vector<bool> > vis(n, vector<bool>(m, false));        for (int i = 0; i < n; ++i) {            for (int j = 0; j < m; ++j) {                if (board[i][j] == word[0]) {                    vis[i][j] = true;                    dfs(board, vis, word, i, j, 0, ans);                    vis[i][j] = false;                    if (ans) return true;                }            }        }        return false;    }        void dfs(vector<vector<char> >& board, vector<vector<bool> >& vis, string word, int x, int y, int loc, bool& ans) {        if (ans) return;        if (board[x][y] != word[loc]) return;                if (loc == word.length() - 1) {            ans = true;            return;        }                for (int i = 0; i < 4; ++i) {            int xx = x + dir[i][0];            int yy = y + dir[i][1];                        if (xx < 0 || yy < 0 || xx >= board.size() || yy >= board[0].size()) continue;            if (vis[xx][yy]) continue;                        vis[xx][yy] = true;            dfs(board, vis, word, xx, yy, loc+1, ans);            vis[xx][yy] = false;        }    }};


原创粉丝点击