您的位置:首页 > 其它

word Search

2015-12-01 22:29 369 查看
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 = [ ['A','B','C','E'],

    ['S','F','C','S'],

    ['A','D','E','E'] ]

word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;

class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();

vector<vector<bool>> visited(m,vector<bool>(n,false));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j] == word[0]){
if(dfs(i,j,0,board,word,visited))
return true;
}
}
}
return false;
}

bool dfs(int x,int y,int curr,vector<vector<char>>& board,
string& word,vector<vector<bool>>& visited){

int m = board.size();
int n = board[0].size();

if(curr == word.size())  return true;

if(x<0 || x>=m || y<0 || y>=n) return false;

if(board[x][y] != word[curr])  return false;

if(visited[x][y] == true) return false;

visited[x][y] = true;
bool ret= dfs(x, y+1, curr+1, board, word,visited) ||
dfs(x+1, y, curr+1, board, word,visited) ||
dfs(x, y-1, curr+1, board, word,visited) ||
dfs(x-1, y, curr+1, board, word,visited);
visited[x][y] = false;
return ret;
}
};

int main()
{

vector<vector<char>> board{{'a','a'}};
Solution s;
cout << s.exist(board, "aaa") << endl;
return 0;

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