回溯法(1)

题目:

回溯法(1)_第1张图片
回溯法(1)_第2张图片

程序:

#include 
#include 

using namespace std;

void findTreasureCore(size_t row, size_t column, 
	vector<vector<int>> &grid, vector<vector<int>> &visited)
{
	size_t rows = grid.size();
	size_t columns = grid[0].size();
	if (rows <= 0 || columns <= 0)
	{
		return;
	}

	if (row >= 0 && row < rows && column >= 0 && column < columns 
		&& 0 == visited[row][column])
	{
		if (1 == grid[row][column])
		{
			visited[row][column] = 1;
			findTreasureCore(row - 1, column, grid, visited);
			findTreasureCore(row, column - 1, grid, visited);
			findTreasureCore(row + 1, column, grid, visited);
			findTreasureCore(row, column + 1, grid, visited);
		}
		if (9 == grid[row][column])
		{
			visited[row][column] = 9;
			return;
		}
		if (0 == grid[row][column])
		{
			visited[row][column] = 1;
			return;
		}
	}
}

int findTreasure(vector<vector<int>> &grid)
{
	size_t rows = grid.size();
	size_t columns = grid[0].size();
	if (rows <= 0 || columns <= 0)
	{
		return 0;
	}

	vector<vector<int>> visited(rows, vector<int>(columns));
	for (size_t i = 0; i < rows; ++i)
	{
		for (size_t j = 0; j < columns; ++j)
		{
			visited[i][j] = 0;
		}
	}

	findTreasureCore(0, 0, grid, visited);

	for (size_t i = 0; i < rows; ++i)
	{
		for (size_t j = 0; j < columns; ++j)
		{
			if (9 == visited[i][j])
			{
				return 1;
			}
		}
	}

	return 0;
}

 void test()
 {
	 int rows, columns;
	 cin >> rows>> columns;
	 vector<vector<int>> grid(rows, vector<int>(columns));
	 for (size_t i = 0; i < grid.size(); ++i)
	 {
		 for (size_t j = 0; j < grid[0].size(); ++j)
		 {
			 cin >> grid[i][j];
		 }
	 }

	 cout << findTreasure(grid) << endl;
 }

int main() 
{
	test();

	return 0;
}

你可能感兴趣的:(回溯法,算法,笔试算法之路)