2023.2.11普及组 搜索

华年的小年华 2023-02-11 13:50:33

第一题

#include <iostream>

using namespace std;

const int N = 10;

int n;
int path[N];

void dfs(int u, int sum, int last)
{
	if (sum == n)
	{
		for (int i = 0; i < u; i ++ ) 
		{
			if (i == 0) printf("%d", path[i]);
			else printf("+%d", path[i]);
		}
			
		puts("");
		return;
	}
	for (int i = last; i < n; i ++ )
	{
		if (sum + i > n) break;
		path[u] = i;
		dfs(u + 1, sum + i, i);
	}
}

int main()
{
	cin >> n;
	
	dfs(0, 0, 1);
	
	return 0;
} 

第二题

#include <iostream>

using namespace std;

const int N = 15;

int n, m, t;
bool st[N][N];
int x1, y1, x2, y2;
int xa, yb;
int cnt;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};


void dfs(int x, int y)
{
	if (x == x2 && y == y2) 
	{
	    cnt ++ ; 
	    return;
	}
	
	for (int i = 0; i < 4; i ++ ) 
	{
		int a = x + dx[i], b = y + dy[i];
		if (a <= 0 || a > n || b <= 0 || b > m || st[a][b] == true) continue;
		if (st[a][b]) continue;
		
		st[a][b] = true;
		dfs(a, b);
		st[a][b] = false;
	}
}

int main()
{
	cin >> n >> m >> t;
	cin >> x1 >> y1 >> x2 >> y2;
	while (t -- )
	{
		cin >> xa >> yb;
		st[xa][yb] = true;
	}
	st[x1][y1] = true;
	dfs(x1, y1);
	cout << cnt << endl;

	return 0;
}

第三题:

#include <iostream>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;

const int N = 110;

int n, m;
bool st[N][N];
PII q[N * N];
char g[N][N];

void bfs(int sx, int sy)
{	
	int hh = 0, tt = -1;
	q[ ++ tt] = {sx, sy};
	st[sx][sy] = true;
	
	while (hh <= tt)
	{
		auto t = q[hh ++ ];
		
		for (int i = t.x - 1; i <= t.x + 1; i ++ )
			for (int j = t.y - 1; j <= t.y + 1; j ++ ) 
			{
				if (i == t.x && j == t.y) continue;
				if (i < 0 || i >= n || j < 0 || j >= m) continue;
				if (st[i][j] || g[i][j] == '.') continue;
				
				q[ ++ tt] = {i, j};
				st[i][j] = true;
			}
	}
}

int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i ++ ) cin >> g[i];
			
	int cnt = 0;
	for (int i = 0; i < n; i ++ ) 
		for (int j = 0; j < m; j ++ ) 
			if (g[i][j] == 'W' && !st[i][j])
			{
				bfs(i, j);
				cnt ++ ;
			}
				
	cout << cnt << endl;
	
	return 0;
} 

 

...全文
32 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50,854

社区成员

发帖
与我相关
我的任务
社区描述
和众多高校算法内卷分子,一起学习和交流算法那。浓郁的算法交流氛围,拒绝躺平,有效内卷。加入我们,私信我拉你入核心内卷群。
算法数据结构leetcode 个人社区
社区管理员
  • 执 梗
  • Dream-Y.ocean
  • ღCauchyོꦿ࿐
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

 刷题!

试试用AI创作助手写篇文章吧