2022年2月7日 星期一

c129: 00572 – Oil Deposits

解題心得

因為沒有固定的起始點,所以這樣寫(?

程式碼

#include <iostream>
using namespace std;

char map[101][101];
bool isVisited[101][101] = { false };
int m, n;

void bfs(int x, int y, char c)
{
	map[x][y] = 'x';
	isVisited[x][y] = true;
	int dx[8] = { -1,-1,-1,0,0,1,1,1 } , dy[8] = { -1,0,1,-1,1,-1,0,1 };
	for (int i = 0; i < 8; i++)
	{
		int nextX = x + dx[i], nextY = y + dy[i];
		if (nextX >= 0 && nextX < m && nextY >= 0 && nextY < n && map[nextX][nextY] == c && !isVisited[nextX][nextY])
			bfs(nextX, nextY, c);
	}
}
int main()
{
	int counter = 1;
	

	while (cin >> m >> n)
	{
		if (m == 0 && n == 0) break;
		for (int i = 0; i < 101; i++)
			for (int j = 0; j < 101; j++)
				isVisited[i][j] = false;
		for (int i = 0; i < m; i++)
			for (int j = 0; j < n; j++)
				cin >> map[i][j];

		int ans = 0;
		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (map[i][j] == '@' && !isVisited[i][j])
					bfs(i, j, '@'), ans++;
			}
		}
		cout << ans << endl;
	}

	return 0;
}

沒有留言:

張貼留言