标签:style blog color strong os for
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
本题用深度搜索即可
class Solution { public: typedef vector<vector<bool> > VVB; typedef vector<vector<char> > VVC; const int dx[4] = {0,1,0,-1}; const int dy[4] = {1,0,-1,0}; int n,m; VVC board; string word; bool dfs(int x, int y,int index,VVB &visit){ if(index == word.length()) return true; if(x>=0 && x <n && y>=0 && y < m && !visit[x][y] && board[x][y] == word[index]){ visit[x][y] = true; for(int i = 0 ; i < 4; ++ i){ if(dfs(x+dx[i], y+dy[i],index+1,visit)) return true; } visit[x][y] = false; } return false; } bool exist(VVC &board, string word) { this->board = board; this->word = word; n = board.size(); m = board[0].size(); VVB visit(n,vector<bool>(m,false)); for(int i = 0 ; i < n; ++i ){ for(int j = 0 ; j < m ;++ j){ if(dfs(i,j,0,visit)) return true; } } return false; } };
Leetcode Word Search,布布扣,bubuko.com
标签:style blog color strong os for
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3826258.html