Word Search [leetcode]

来源:互联网 发布:oimo.js 编辑:程序博客网 时间:2024/06/03 14:55

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

bool exist(vector<vector<char> > &board, string word) {        int m = board.size();        if (m == 0) return false;        int n = board[0].size();        if (n == 0) return false;        if (word.size() == 0) return false;        vector<int> x;        vector<int> y;        for (int i = 0; i < m; i++)            for (int j = 0; j < n; j++)                if (board[i][j] == word[0])                {                    x.push_back(i);                    y.push_back(j);                }                        for (int i = 0; i < x.size(); i++)        {            if (dfs(board, word, 1, x[i], y[i], m, n)) return true;        }        return false;    }        bool dfs(vector<vector<char> > &board, string& word, int index, int x, int y, int m, int n)    {        if (index == word.size()) return true;        char temp = board[x][y];        board[x][y] = '.';        bool res = false;        if (x > 0 && board[x - 1][y] == word[index])            res |= dfs(board, word, index + 1, x - 1, y, m, n);        if (res) return true;        if (x < m - 1 && board[x + 1][y] == word[index])            res |= dfs(board, word, index + 1, x + 1, y, m, n);        if (res) return true;        if (y > 0 && board[x][y - 1] == word[index])            res |= dfs(board, word, index + 1, x, y - 1, m, n);        if (res) return true;        if (y < n - 1 && board[x][y + 1] == word[index])            res |= dfs(board, word, index + 1, x, y + 1, m, n);        if (res) return true;                board[x][y] = temp;        return res;    }


0 0