81分bfs求助,数据保证荷花无环吗
查看原帖
81分bfs求助,数据保证荷花无环吗
992080
Divinsword_Liao楼主2024/1/14 16:48

wa 测试点#2#5#15(计数错误)

代码

#include <bits/stdc++.h>
using namespace std;
int fx[] = {1, 1, -1, -1, 2, 2, -2, -2};
int fy[] = {2, -2, 2, -2, 1, -1, 1, -1};
int n, m, ex, ey;	//ex, ey终点坐标
char ch[35][35];
struct square
{
	int step;
	long long num;
} s[35][35];	//step到此点所需莲花,num到此点最短路数量
bool b[35][35];	//是否到过
inline bool check(int x, int y) {	return x <= m && x > 0 && y <= n && y > 0 && ch[x][y] != '2';	}	//判断能不能走
queue<int> qx, qy, ax, ay;//ax,ay为可走的有莲花的点
int main()
{
	cin >> m >> n;
	for (int i = 1; i <= m; i ++)
		for(int j = 1; j <= n; j ++)
		{
			cin >> ch[i][j];
			if (ch[i][j] == '3')
				qx.push(i), qy.push(j), s[i][j].num = 1, s[i][j].step = 0, b[i][j] = 1;
			if (ch[i][j] == '4')
				ex = i, ey = j;
		}
	int x, y, lx = 0, ly = 0, now = 0;
	while (!qx.empty() || !ax.empty())	//没有!ax.empty()少6分(wa#9)
	{
		if (qx.empty() || now != s[qx.front()][qy.front()].step)
			if (!ax.empty())
				x = ax.front(), y = ay.front(), ax.pop(), ay.pop();
			else
				x = qx.front(), y = qy.front(), now = s[x][y].step, qx.pop(), qy.pop();
		else
			x = qx.front(), y = qy.front(), qx.pop(), qy.pop();
		for (int i = 0; i < 8; i ++)
			if (check(x + fx[i], y + fy[i]))
			{
				int nx = x + fx[i], ny = y + fy[i];
				if (ch[nx][ny] == '1')
				{
					if (!b[nx][ny])
					{
						s[nx][ny].step = s[x][y].step;
						ax.push(nx);	ay.push(ny);
						s[nx][ny].num += s[x][y].num;
						b[nx][ny] = 1;
					}
					else if (s[nx][ny].step == s[x][y].step)
						s[nx][ny].num += s[x][y].num;
					continue;
				}
				if (!b[nx][ny])
				{
					s[nx][ny].step = s[x][y].step + 1;
					s[nx][ny].num += s[x][y].num;
					qx.push(nx);	qy.push(ny);
					b[nx][ny] = 1;
				}
				else if (s[nx][ny].step == s[x][y].step + 1)
					s[nx][ny].num += s[x][y].num;
			}
	}
	if (b[ex][ey])
		cout << s[ex][ey].step - 1 << endl << s[ex][ey].num << endl;
	else cout << - 1 << endl;
	return 0;
}

#2答案2040,我输出1800

2024/1/14 16:48
加载中...