79. Word Search

来源:互联网 发布:麦振鸿 知乎 编辑:程序博客网 时间:2024/06/15 10:01

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.

回溯法,因为要求数组中每个元素只能使用一次,故应该对每个元素位设置一个标志,表示其已用并不可用;

bool isexist(vector<vector<char>>& board, int row, int& rows, int col, int& cols, string& word, int pos, vector<vector<bool>>& flag){    if (pos == word.size()) return true;    if (row < 0 || row >= rows || col < 0 || col >= cols || flag[row][col] || board[row][col] != word[pos])return false;    if (board[row][col] == word[pos]){        flag[row][col] = true;        if (isexist(board, row - 1, rows, col, cols, word, pos + 1, flag) ||            isexist(board, row + 1, rows, col, cols, word, pos + 1, flag) ||            isexist(board, row, rows, col - 1, cols, word, pos + 1, flag) ||            isexist(board, row, rows, col + 1, cols, word, pos + 1, flag))            return true;        flag[row][col] = false;    }    return false;}bool exist(vector<vector<char>>& board, string word) {    if (word == "" || board.size() == 0)return false;    int rows = board.size(), cols = board[0].size();    vector<vector<bool>> flag(rows, vector<bool>(cols, false));    for (int i = 0; i < rows; i++){        for (int j = 0; j < cols; j++){            if (board[i][j] == word[0])                if (isexist(board, i, rows, j, cols, word, 0, flag))return true;        }    }    return false;}
原创粉丝点击