深搜入门221

已结束 ACM/ICPC 开始于: 2025-2-21 14:00 340 小时 主持人: 22

一路走到头,不撞墙不回头

——深度优先搜索

#include <bits/stdc++.h>
using namespace std;
int n, m;

//优先级右下左上
int xm[5] = {0, 0, 1, 0, -1}; //右下左上
int ym[5] = {0, 1, 0, -1, 0};
int a[100][100];
void dfs(int x, int y, int k) {
	a[x][y] = k;
	for (int i = 1; i <= 4; i++) {
		int tx = x + xm[i]; //当i=1
		int ty = y + ym[i];
		if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && a[tx][ty] == 0) {
			dfs(tx, ty, k + 1);
		}
	}

}

//depth first search深度优先搜索

int main() {

	cin >> n >> m;
	dfs(1, 1, 1); //(1,1)的值是1
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << setw(3) << a[i][j];
		}
		cout << endl;
	}

}

状态
已结束
规则
ACM/ICPC
题目
4
开始于
2025-2-21 14:00
结束于
2025-3-7 18:00
持续时间
340 小时
主持人
参赛人数
22