Leetcode算法79 Word Search

来源:互联网 发布:oppo手机root软件 编辑:程序博客网 时间:2024/06/05 16:48

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.

利用深度优先算法代码:

class Solution {public:  bool exist(vector<vector<char > >& board, string word) {if (word.length() == 0){return true;}char c = word[0];bool res = false;for (int i = 0; i < board.size(); i++){for (int j = 0; j < board[0].size(); j++){if (board[i][j] == c){board[i][j] = '.';res = search(board, word, i, j, 1);board[i][j] = c;if (res){return res;}}}}return res;}bool search(vector<vector<char>> &board, string word, int low, int row, int index){if (index == word.length()){return true;}bool res = false;char c = word[index];if (low>0 && board[low - 1][row] == c){board[low - 1][row] = '.';res = search(board, word, low - 1, row, index + 1);if (res)return res;board[low - 1][row] = c;}if (low < (board.size() - 1) && board[low + 1][row] == c){board[low + 1][row] = '.';res = search(board, word, low + 1, row, index + 1);if (res)  return res;board[low + 1][row] = c;}if (row > 0 && board[low][row - 1] == c){board[low][row - 1] = '.';res = search(board, word, low, row - 1, index + 1);if (res) return res;board[low][row - 1] = c;}if (row < board[0].size() - 1 && board[low][row + 1] == c){board[low][row + 1] = '.';res = search(board, word, low, row + 1, index + 1);if (res) return res;board[low][row + 1] = c;}return res;}};


0 0
原创粉丝点击