首页 > 其他 > 详细

leetcode 之 Word Search

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!