Word Search问题及解法

来源:互联网 发布:linux epoll socket 编辑:程序博客网 时间:2024/05/18 17:44

问题描述:

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.

示例:

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.

问题分析:

此类查找问题,可采用回溯法。


过程详见代码:

class Solution {public:    bool exist(vector<vector<char>>& board, string word) {if (word.empty()) return false;int m = board.size();int n = board[0].size();vector<vector<int>> used(m,vector<int>(n, 0));for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){if (board[i][j] == word[0]){bool res = search(board, word, i, j, 1, used);if (res) return true;}}}return false;}bool search(vector<vector<char>>& board, string word, int i, int j, int k, vector<vector<int>>& used){used[i][j] = 1;if (k == word.length()){if (board[i][j] == word[k - 1]) return true;}if (board[i][j] == word[k - 1]){bool res = false;if (j < board[0].size() - 1 && !used[i][j + 1]){res = res || search(board, word, i, j + 1, k + 1, used);if (res) return true;}if (i + 1 < board.size() && !used[i + 1][j]){res = res || search(board, word, i + 1, j, k + 1, used);if (res) return true;}if (j - 1 >= 0 && !used[i][j - 1]){res = res || search(board, word, i, j - 1, k + 1, used);if (res) return true;}if(i - 1 >= 0 && !used[i - 1][j]){res = res || search(board, word, i - 1, j, k + 1, used);if (res) return true;}used[i][j] = 0;return res;}used[i][j] = 0;return false;}};


原创粉丝点击