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

Surrounded Regions

时间:2014-12-26 21:38:20      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

该题目主要考察了堆栈和深度优先搜索的知识点。在递归深度太深导致运行出错是,可以采用栈保存结果,减小递归的深度。

详细代码如下:

class Solution {
public:
     stack<pair<int,int>> data;
    void solve(vector<vector<char>> &board) {
	
       if(board.size() == 0)
	      return ;
	  GetPoint(board);
	  WriteResult(board);
		
        
    }
	void GetPoint(vector<vector<char>> &board)
	{
       int i =0;
	  	 pair<int,int> temp;
	  	 for (i=0; i<board[0].size();i++)
	  	 {
    	       temp.first  = 0;
    	  	   temp.second = i;
    	  	   ExtendPoint(board,temp);
    	  
    	  	   temp.first  = board.size()-1;
    	  	   temp.second = i;
    	  	   ExtendPoint(board,temp);
	  
	  	 }
	  
	  	 for (i=0; i<board.size();i++)
	  	 {
		       temp.first  = i;
		  	   temp.second = 0;
		  	   ExtendPoint(board,temp);
		  
		  	   temp.first  = i;
		  	   temp.second = board[0].size()-1;
		  	   ExtendPoint(board,temp);
	  
	  	 }
        while(data.size() !=0)
        {
			temp = data.top();
			data.pop();
			ExtendPoint(board,temp);

		}
		 

	}
	void ExtendPoint(vector<vector<char>> &board,pair<int,int> point)
	{
    	if(point.first < 0 || point.first >= board.size())
		  return ;
		if(point.second <0 || point.second >=  board[0].size())
		 return ;
		int x,y;
		pair<int,int> temp;
		x= point.first;
		y= point.second;
		if(board[x][y] == ‘X‘ || board[x][y] == ‘A‘)
		 return ;
		board[x][y] = ‘A‘;

		temp.first  = x-1;
		temp.second = y;
		data.push(temp);

		temp.first  = x+1;
		temp.second = y;
		data.push(temp);

		temp.first  = x;
		temp.second = y-1;
		data.push(temp);

		temp.first  = x;
		temp.second = y+1;
		data.push(temp);

	

	}
	void WriteResult(vector<vector<char>> &board)
	{
	   int i,j;
	 
		for (i=0; i< board.size(); i++)
		    for(j=0; j< board[i].size();j++)
		    {
		       if(board[i][j] == ‘A‘)
		       {
				   board[i][j] = ‘O‘;

			   }
			   else if(board[i][j] == ‘O‘)
			   {
				    board[i][j] = ‘X‘;
			   }

			}


	}
	
	
	
};

 

Surrounded Regions

标签:

原文地址:http://www.cnblogs.com/xgcode/p/4187515.html

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