标签:
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
,"SEE"
,
-> returns true
,"ABCB"
,
-> returns false
.
Subscribe to see which companies asked this question
class Solution { public: bool find(vector<vector<char>> &board, vector<vector<int>> &visited, string word, int row, int col, int cnt, int used) { int rows = board.size(), cols = board[0].size(); if(cnt==word.length()) return true; if(row >= rows || col >= cols || row < 0 || col < 0) return false; if(visited[row][col] == 1) return false; if(board[row][col]!=word[cnt]) return false; if(used >= rows*cols) return false; visited[row][col] = 1; used += 1; //cout << "row="<<row<<" col=" << col << board[row][col] << endl; bool flag1=find(board, visited, word, row+1, col, cnt+1, used); if(flag1) return true; bool flag2=find(board, visited, word, row, col+1, cnt+1, used); if(flag2) return true; bool flag3=find(board, visited, word, row-1, col, cnt+1, used); if(flag3) return true; bool flag4=find(board, visited, word, row, col-1, cnt+1, used); if(flag4) return true; visited[row][col]=0; used-=1; return false; } bool exist(vector<vector<char>> &board, string word) { int rows=board.size(), cols=0, len=word.length(); if(rows==0) return false; if(len==0) return true; cols = board[0].size(); bool ret = false; vector<vector<int>> visited(rows, vector<int>(cols,0)); for(int i=0; i < rows; i++) { for(int j=0; j < cols; j++) { if(board[i][j]==word[0]) { ret = find(board, visited, word, i, j, 0, 0); if(ret==true) return true; } } } return false; } };
标签:
原文地址:http://blog.csdn.net/suichen1/article/details/51335422