leetcode 56: Word Search

Word SearchApr 18 '12

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.
uncompleted


class Position{
public:
    int x;
    int y;
    Position(int xx, int yy) : x(xx),y(yy){};
    
};

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(word.size() ==0) return true;
        if(board.size()==0) return false;
        Solution::m = board.size();
        Solution::n = board[0].size();
        vector<bool> temp(n,false);
        vector<vector<bool> > flags(m, temp);
        
        for( int i=0; i<m; i++) {
            for( int j=0; j<n; j++) {
                if(board[i][j]==word[0]){
                    flags[i][j] = true;
                    if( dfs( board, word, flags, 0, Position(i, j) ) ) return true;
                    flags[i][j] = false;
                }
            }
        }
        return false;
    }
    
private:
    int m;
    int n;
    
    bool dfs( vector<vector<char> > &board, string & word, vector<vector<bool> >& flags, int level,Position p ) {
        if( level == word.size()-1) return true;
        if( word[level] != board[p.x][p.y]) return false;
        for( int i=-1; i<=1; i++) {
            for( int j=-1; j<=1; j++) {
                if(i+j!=1 && i+j!=-1) continue;
                if( p.x+i>=0 && p.y+j>=0 && p.x+i<m && p.y+j<n && !flags[p.x+i][p.y+j] ) {
                    flags[p.x+i][p.y+j] = true;
                    if( dfs(board, word, flags, level+1, Position( p.x+i, p.y+j) ) )
                        return true;
                    else
                        flags[p.x+i][p.y+j] == false;
                }
            }
        }
        return false;
    }
};


posted @ 2013-01-27 09:48  西施豆腐渣  阅读(141)  评论(0编辑  收藏  举报