您的位置:首页 > 其它

[Leetcode 79, Medium] Word Search

2015-07-24 21:28 375 查看
Problem:

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
.

Analysis:

Solutions:

C++:

bool SearchAux(vector<vector<char>>& board, const string& word, int search_index, int x, int y)
    {
        int size = word.size();
        int rows = board.size();
        int cols = board[0].size();
        
        for(int i = -1; i <= 1; ++i) {
            for(int j = -1; j <= 1; ++j) {
                if((i == 0 && j !=0) || (i != 0 && j == 0)) {
                    if(x + i < 0 || x + i >= rows || y + j < 0 || y +j >= cols 
                        || board[x + i][y + j] != word[search_index])
                        continue;
                    
                    if(search_index == word.size() - 1)
                        return true;
                    board[x + i][y + j] = '#';
                    if(SearchAux(board, word, search_index + 1, x + i, y + j))
                        return true;
                    board[x + i][y + j] = word[search_index];
                }
            }
        }
        
        return false;
    }

    bool exist(vector<vector<char>>& board, string word) {
        if(board.empty() || word.empty())
            return false;
            
        vector<pair<int, int> > starts;
        for(int i = 0; i < board.size(); ++i) {
            for(int j = 0; j < board[0].size(); ++j) {
                if(board[i][j] == word[0])
                    starts.push_back(make_pair(i, j));
            }
        }
        
        if(word.size() == 1 && starts.size() > 0)
            return true;
        
        for(int i = 0; i < starts.size(); ++i) {
            board[starts[i].first][starts[i].second] = '#';
            if(SearchAux(board, word, 1, starts[i].first, starts[i].second))
                return true;
            board[starts[i].first][starts[i].second] = word[0];
        }
        
        return false;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: