码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 之 Word Search

时间:2014-09-06 22:34:14      阅读:261      评论:0      收藏:0      [点我收藏+]

标签: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,
word = "SEE", -> returns true,
word = "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;
    }
};

 

leetcode 之 Word Search

标签:word search   search   leetcode   

原文地址:http://blog.csdn.net/fangjian1204/article/details/39104767

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!