dfs求调
查看原帖
dfs求调
1158874
huashenek楼主2024/3/14 17:32
#define  _CRT_SECURE_NO_WARNINGS
#include<map>
#include<cmath>
#include<stack>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<iomanip>
#define MAXLEN 1005
using namespace std;
typedef long long ll;   
using namespace std;
int n, m, x, y;
int chess[405][405];
bool ka[405][405];
int dx[] = {2,1,-1,-2,-2,-1,1,2};
int dy[] = {1,2,2,1,-1,-2,-2,-1};
void dfs(int a, int b,int num) {
	//起始位置
	for (int i = 0; i < 8; i++) {
		int nx = a + dx[i];
		int ny = b + dy[i];
		if (nx<1 || ny<1 || nx>n || ny>m) {
			continue;
		}
		if (ka[nx][ny]) {
			continue;
		}
		if (num >= chess[nx][ny]) {
			continue;
		}
		chess[nx][ny] = min(chess[nx][ny], num);
		ka[nx][ny] = true;
		dfs(nx, ny, num + 1);
		ka[nx][ny] = false;
	}
}
int main() {
	cin >> n >> m >> x >> y;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			chess[i][j] = 9999999;
		}
	}
	ka[x][y] = true;
	chess[x][y] = 0;
	dfs(x, y, 1);

	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (chess[i][j] == 9999999) {
				chess[i][j] = -1;
			}
			cout << chess[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}

卡在第八个测试点了

2024/3/14 17:32
加载中...