您的位置:首页 > 其它

【leetcode】79. Word Search

2015-10-08 20:05 489 查看
简单的dfs

/**
*  @author         johnsondu
*  @time           20:01 8th Oct 2015
*  @type           dfs
*  @url            https://leetcode.com/problems/word-search/ *  @status         Accepted
*/

class Solution {
public:
void dfs(int x, int y, int idx, int len, int row, int col, vector<vector<bool>> &mark, bool &flag, vector<vector<char>>& board, string word)
{
if(flag) return;
if(word[idx] != board[x][y]) return;
if(idx == len - 1) {
flag = true;
return;
}

int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
for(int k = 0; k < 4; k ++) {
int tx = x + dir[k][0];
int ty = y + dir[k][1];
if(tx >= row || ty >= col || tx < 0 || ty < 0) continue;
if(mark[tx][ty]) continue;
mark[tx][ty] = true;
dfs(tx, ty, idx + 1, len, row, col, mark, flag, board, word);
mark[tx][ty] = false;
}

}

bool exist(vector<vector<char>>& board, string word) {
if(board.size() == 0) return false;
if(word.size() == 0) return true;
int row = board.size();
int col = board[0].size();
vector<vector<bool>> mark(board.size(), vector<bool>(board[0].size(), false));
bool flag = false;
int len = word.size();
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
if(board[i][j] == word[0]) {
mark[i][j] = true;
dfs(i, j, 0, len, row, col, mark, flag, board, word);
mark[i][j] = false;
if(flag) return flag;
}
}
}
return flag;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: