您的位置:首页 > 其它

[Leetcode 69] 79 Word Search

2013-07-20 08:24 316 查看
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:

This is a typical DFS problem. The possible start state is each character of the given board. But the possible intermediate state can only be forwarding a more step from the current state into one of four directions (up, down, right, left).

Some of the optimizations are

1. in-place tracking of whether a position is visited (change b[i][j] into '#' to indicate it has been visited)

2. directions[][] array uaeage to reduce the code

Code:

class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
w = word;
row = board.size();
col = board[0].size();

bool e = false;

string ww = "";
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
if (board[i][j] == word[0]) {
ww.push_back(board[i][j]);
board[i][j] = '#';
dfs(ww, i, j, board, e);
board[i][j] = word[0];
ww.erase(ww.end()-1);
if (e) return true;
}
}
}

return false;
}

private:
string w;
int col, row;
int direct[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

bool isValid(int x, int y, vector<vector<char> > &b)
{
return ((x>=0 && x<row) && (y>=0 && y<col) && (b[x][y] != '#'));
}

void dfs(string s, int i, int j, vector<vector<char> > &b, bool &res)
{
if (s[s.length()-1] != w[s.length()-1]) return ;

if (s.length() == w.length()) {
if (s == w)
res = true;

return ;
}

for (int k=0; k<4; k++) {
int ii = i + direct[k][0];
int jj = j + direct[k][1];

if (isValid(ii, jj, b)) {
s.push_back(b[ii][jj]);
b[ii][jj] = '#';
dfs(s, ii, jj, b, res);
b[ii][jj] = s.back();
s.erase(s.end()-1);
}

if (res) return ;
}

return ;
}
};


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