码迷,mamicode.com
首页 > 其他好文 > 详细

Word Search -- leetcode

时间:2015-04-14 13:03:34      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:leetcode   search   word   board   

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.


基本思路:

1. 对棋盘每个点进行深度优搜索。

2. 传统Ascii码,只会用7bit,最高bit为0. 故可用此bit位,复用作访问标志位。



class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        if (board.empty() || board[0].empty()) return false;
        
        for (int i=0; i<board.size(); i++) {
            for (int j=0; j<board[0].size(); j++) {
                if (exist(board, word, 0, i, j))
                    return true;
            }
        }
        
        return false;
    }
    
    bool exist(vector<vector<char> >&board, const string &word, int index, int x, int y) {
        if (index == word.size()) return true;
        if (x<0 || y<0 || x==board.size() || y==board[0].size()) return false;
        if (board[x][y] != word[index]) return false;
        
        board[x][y] ^= 128;
        const bool existed = exist(board, word, index+1, x, y+1) ||
                             exist(board, word, index+1, x, y-1) ||
                             exist(board, word, index+1, x+1, y) ||
                             exist(board, word, index+1, x-1, y);
        board[x][y] ^= 128;
        
        return existed;
    }
};


Word Search -- leetcode

标签:leetcode   search   word   board   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45039107

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!