964: 数细胞

样例:

解法:

1.遍历矩阵

2.判断矩阵[i][j],若是未标记细胞则遍历相邻所有未标记细胞并标记,且计数

实现:遍历相邻所有未标记细胞

以DFS实现:

function dfs(当前状态) {
	if (终止条件) {

	}
    vis[标记当前状态]
	for (寻找新状态) {
		if (状态合法) {
			dfs(新状态)
			//看情况是否需要重置vis[]
		}
	}
}

代码

#include<iostream>
#include<vector>
using namespace std;
int dir[4][2] = { 0,1,1,0,-1,0,0,-1 };
void dfs(vector<vector<int>>& a, int x, int y) {
	if (a[x][y] == 0) return;
	a[x][y] = 0;
	for (int i = 0; i < 4; i++) {
		int nextx = x + dir[i][0];
		int nexty = y + dir[i][1];
		if (nextx < 0 || nextx >= a.size() || nexty < 0 || nexty >= a[0].size()) {
			continue;
		}
		if (a[nextx][nexty] != 0) {
			dfs(a, nextx, nexty);
		}
	}
}
int main() {
	int m, n;
	cin >> m >> n;
	vector<vector<int>> a(m, vector<int>(n , 0));
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++)
			cin >> a[i][j];
	int result = 0;
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (a[i][j] != 0) {
				result++;
				dfs(a, i, j);
			}
		}
	}
	cout << result;
	return 0;
}

以BFS实现:

function bfs(当前节点) {
	当前节点入列
	标记当前节点
	while (队列不为空) {
		当前节点出列
		寻找合法相邻节点
        合法相邻节点入列
		标记相邻节点
	}
}

代码:

#include<iostream>
#include<vector>
#include<queue>
#include<utility>
using namespace std;
int dir[4][2] = { 0,1,1,0,-1,0,0,-1 };
void bfs(vector<vector<int>>& a, int x, int y) {
	queue<pair<int, int>> que;
	que.push({ x,y });
	a[x][y] = 0;
	while (!que.empty()) {
		pair<int, int> cur = que.front();
		que.pop();
		int curx = cur.first;
		int cury = cur.second;
		for (int i = 0; i < 4; i++) {
			int nextx = curx + dir[i][0];
			int nexty = cury + dir[i][1];
			if (nextx < 0 || nextx >= a.size() || nexty < 0 || nexty >= a[0].size()) {
				continue;
			}
			if (a[nextx][nexty] != 0) {
				que.push({ nextx,nexty });
				a[nextx][nexty] = 0;
			}
		}
	}
}
int main() {
	int m, n;
	cin >> m >> n;
	vector<vector<int>> a(m, vector<int>(n, 0));
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++)
			cin >> a[i][j];
	int result = 0;
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (a[i][j] != 0) {
				result++;
				bfs(a, i, j);
			}
		}
	}
	cout << result;
	return 0;
}

相关推荐

  1. 细胞培养之一二三:哺乳动物细胞培养相关问题

    2024-04-14 21:26:02       64 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-14 21:26:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-14 21:26:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-14 21:26:02       87 阅读
  4. Python语言-面向对象

    2024-04-14 21:26:02       96 阅读

热门阅读

  1. 合并两个有序数组讲解

    2024-04-14 21:26:02       39 阅读
  2. mac安装nvm

    2024-04-14 21:26:02       37 阅读
  3. [前端][杂项] React版本

    2024-04-14 21:26:02       40 阅读
  4. 分层风格的软件架构设计概念及其实际应用

    2024-04-14 21:26:02       36 阅读
  5. vue--检测对象,数组的改变

    2024-04-14 21:26:02       43 阅读
  6. 【Redis】事务

    2024-04-14 21:26:02       39 阅读
  7. 移除元素总结(十九天)

    2024-04-14 21:26:02       42 阅读
  8. 深入理解nginx的userid模块

    2024-04-14 21:26:02       38 阅读