POJ 1979——Red and Black

難度分析——簡單

Description:
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.

Write a program to count the number of black tiles which he can reach by repeating the moves described above.

翻譯
有一個長方形的房間,覆蓋着正方形的瓷磚。每個磁貼都被着色爲紅色或黑色。一個人站在黑色的瓷磚上。他可以從一個圖塊移動到四個相鄰圖塊之一。但是他不能在紅色瓷磚上移動,只能在黑色瓷磚上移動。

編寫一個程序,通過重複上述動作來計算他可以到達的黑色瓷磚的數量。

問題分析:很明顯,這就是一個迷宮問題,使用深度優先搜索即可得出答案。需要注意的是,走過的路記得做上標記,避免死循環。

代碼:需要注意的是,我這裏迷宮使用的是int類型,題意中得是char類型,這裏我是使用之前做過一題迷宮的地圖。(懶)

#include"bits\stdc++.h"
using namespace std;
const int M = 8;
const int N = 8;
int mg[M + 2][N + 2] =
{
	{ 1,1,1,1,1,1,1,1,1,1 },{ 1,0,0,1,0,0,0,1,0,1 },
	{ 1,0,0,1,0,0,0,1,0,1 },{ 1,0,0,0,0,1,1,0,0,1 },
	{ 1,0,1,1,1,0,0,0,0,1 },{ 1,0,0,0,1,0,0,0,0,1 },
	{ 1,0,1,0,0,0,1,0,0,1 },{ 1,0,1,1,1,0,1,1,0,1 },
	{ 1,1,0,0,0,0,0,0,0,1 },{ 1,1,1,1,1,1,1,1,1,1 }
};
int xi = 1;
int yi = 1;
struct Box
{
	int a, b;//a,b是x,y方向的偏移
};
Box direction[4] =
{
	{ -1,0 },{ 0,1 },{ 1,0 },{ 0,-1 }
};
int mark[M + 2][N + 2];
int k = 1;
void Maze(int x, int y)
{
	int i, g, h;//g,h記錄下一位置的信息
	if (x < 0 || y <0 || x > M - 1 || y > N - 1 || mg[x][y] == 1 || mg[x][y] == -1)
		return;

	k++;
	for (int i = 0; i < 4; i++)
	{
		g = x + direction[i].a;//g = x加上偏移位置
		h = y + direction[i].b;
		mg[x][y] = -1;
		Maze(g, h);
	}
}
int main()
{
	mark[xi][yi] = -1;
	Maze(xi, yi);
	cout << k << endl;
	return 0;
}

當然此代碼稍微修改一下也能解決迷宮問題。

發佈了17 篇原創文章 · 獲贊 20 · 訪問量 5407
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章