LeetCode 79. Word Search Word Search (C ++)

topic:

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.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

analysis:

Given a two-dimensional grid and a word, to find out whether the word exists in the grid.

Words must, by the letters in adjacent cells constituting alphabetically, where "adjacent" cells that are adjacent horizontally or vertically adjacent cells. Letters within the same cell is not allowed to be reused.

A title search, somewhat similar to Maze, except in accordance with a given word in alphabetical order to find the traverse board in each element, and the judgment of the first letter in the word are the same, if the same up and down about the current location search elements are adjacent cell and the next letter is the same as the current letter, letters, or not in the search range of different returns false, when the number of letters is equal to the search word length, it indicates that the word found in the board. Note that each letter is determined to be a mark at the current position of the searched, to prevent reuse letters. I choose to directly change the board elements, so as not to repeat this to determine the position in a subsequent judgment, at the end of the search to come back on it.

program:

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        h = board.size();
        w = board[0].size();
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; ++j){
                if(searchexist(board, word, 0, i, j)) return true;
            }
        }
        return false;
    }
    int searchexist(vector<vector<char>>& board, string &word, int n, int x, int y){
        if(x < 0 || x > h-1 || y < 0 || y > w-1 || word[n] != board[x][y])
            return 0;
        if(n == word.length()-1)
            return 1;
        char temp = board[x][y];
        board[x][y] = 0;
        int flag = searchexist(board, word, n+1, x+1, y)
                 ||searchexist(board, word, n+1, x-1, y)
                 ||searchexist(board, word, n+1, x, y+1)
                 ||searchexist(board, word, n+1, x, y-1);
        board[x][y] = temp;
        return flag;
    }
private:
    int h, w;
};

Guess you like

Origin www.cnblogs.com/silentteller/p/11128108.html