标签:word search search leetcode
Word Search
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
,"SEE"
,
-> returns true
,"ABCB"
,
-> returns false
.
class Solution { public: bool search(vector< vector<char> >& board,int x,int y,string word,vector< vector<bool> >& hasUsed) { if(word.size() == 0)return true; int rows = board.size(),cols = board[0].size(); if(x > 0 && !hasUsed[x-1][y] && board[x-1][y] == word[0])//上方 { hasUsed[x-1][y] = true; if(search(board,x-1,y,word.substr(1),hasUsed))return true; hasUsed[x-1][y] = false; } if(y < cols - 1 && !hasUsed[x][y+1] && board[x][y+1] == word[0])//右方 { hasUsed[x][y+1] = true; if(search(board,x,y+1,word.substr(1),hasUsed))return true; hasUsed[x][y+1] = false; } if(x < rows - 1 && !hasUsed[x+1][y] && board[x+1][y] == word[0])//下方 { hasUsed[x+1][y] = true; if(search(board,x+1,y,word.substr(1),hasUsed))return true; hasUsed[x+1][y] = false; } if(y > 0 && !hasUsed[x][y-1] && board[x][y-1] == word[0])//左方 { hasUsed[x][y-1] = true; if(search(board,x,y-1,word.substr(1),hasUsed))return true; hasUsed[x][y-1] = false; } return false; } bool exist(vector<vector<char> > &board, string word) { int rows = board.size(); if(rows <= 0)return false; int cols = board[0].size(); if(cols <= 0)return false; int i,j; vector< vector<bool> >hasUsed(rows);//用于标记该位置是否走过 for (i = 0;i < rows;i++) { vector<bool> tmp(cols,false); hasUsed[i] = tmp; } for (i = 0;i < rows;i++) { for (j = 0;j < cols;j++) { if(!hasUsed[i][j] && board[i][j] == word[0]) { hasUsed[i][j] = true; if(search(board,i,j,word.substr(1),hasUsed))return true; hasUsed[i][j] = false; } } } return false; } };
标签:word search search leetcode
原文地址:http://blog.csdn.net/fangjian1204/article/details/39104767