AcWing 188. 武士风度的牛

知识点:广搜

李煜东的例题讲的那么难,习题确这么简单,不过这个样子也对,把最精华的东西放到例题里面好好讲讲

#include 

using namespace std;

const int N = 205;

struct node {
	int x, y;
	node() {}
	node(int a, int b): x(a), y(b) {}
};

int n, m, xs, ys, xe, ye;
int dx[8] = {-2, -2, -1, 1, 2, 2, 1, -1};
int dy[8] = {-1, 1, 2, 2, 1, -1, -2, -2};
string s[N];

int bfs() {
	queue q;
	q.push(node(xs, ys));
	int dist[N][N];
	memset(dist, -1, sizeof(dist));
	dist[xs][ys] = 0;
	while (!q.empty()) {
		node now = q.front(); q.pop();
		if (now.x == xe && now.y == ye) return dist[now.x][now.y];
		for (int i = 0; i < 8; i++) {
			int x1 = now.x + dx[i];
			int y1 = now.y + dy[i];
			if (x1 < 1 || x1 > n || y1 < 1 || y1 > m) continue;
			if (dist[x1][y1] != -1 || s[x1][y1] == '*') continue;
			q.push(node(x1, y1));
			dist[x1][y1] = dist[now.x][now.y] + 1;
		}
	}
	return -1;
}

int main() {
	cin >> m >> n;
	for (int i = 1; i <= n; i++) {
		cin >> s[i];
		s[i] = " " + s[i];
		for (int j = 1; j <= m; j++) {
			if (s[i][j] == 'K') { xs = i; ys = j; s[i][j] = '.'; }
			if (s[i][j] == 'H') { xe = i; ye = j; s[i][j] = '.'; }
		}
	}
	cout << bfs();
	return 0;
}

你可能感兴趣的:(加入题解目录题解,算法,图论)