大佬们,这题while scanf怎么调才能让scanf不读入回车?
查看原帖
大佬们,这题while scanf怎么调才能让scanf不读入回车?
593753
LukeSu楼主2022/3/3 20:31

这是一道非常简单的bfs题(就是马跳来跳去找终点), 但是我卡在了程序的输入上:

你们把代码运行一下看一下结果和样例输出的区别。我怀疑是scanf把回车给读进去了?要怎么改呢?搞了好久了还是没搞好呜呜呜o(╥﹏╥)o

#include<bits/stdc++.h>
using namespace std;

const int N = 66;
int g[N][N];
int maxx = 8, maxy = 8;	//定义棋盘的边界 
char ch1, temp1, ch2, temp2;	//获取起点输入,终点输入 
int bx, by, ex, ey;	//起点位置和终点位置

int dx[8] = {1, 1, -1, -1, 2, 2, -2, -2};	//马的步伐 
int dy[8] = {2, -2, 2, -2, -1, 1, 1, -1};
queue< pair<int, int> > q;
int st[N][N] = {};
int dist[N][N]; 	//记录步数 
int xx, yy;

void bfs(){
	while(!q.empty()){
		int x = q.front().first;
		int y = q.front().second;
		q.pop();
		st[x][y] = 1;
		for(int i = 0; i < 8; i++){
			xx = dx[i] + x;
			yy = dy[i] + y;  
		 if(xx >= 1 and xx <= maxx and yy >= 1 and yy <= maxy and st[xx][yy] == 0){
		 	dist[xx][yy] = dist[x][y] + 1;
		 	if(xx == ex and yy == ey){
				return;
		 	}
		 	q.push(make_pair(xx, yy));
		 }
	}
}
}

int main(){
	map<char, int> mp;
	mp['a'] = 1; mp['b'] = 2; mp['c'] = 3; mp['d'] = 4;
	mp['e'] = 5; mp['f'] = 6; mp['g'] = 7; mp['h'] = 8;
	while(scanf("%c%d %c%d", &ch1, &temp1, &ch2, &temp2) != EOF){
		bx = mp[ch1];
		by = temp1;
		ex = mp[ch2];
		ey = temp2;	
		dist[ex][ey] = 0;
		q.push(make_pair(bx, by));
		bfs();
		cout << "To get from " << ch1 << by << " to " << ch2 << ey << " takes " << dist[xx][yy] << " knight moves.";
		memset(st, 0, sizeof st);
		while(!q.empty()) q.pop();
		memset(dist, 0, sizeof dist);	
	}
	return 0; 
}
2022/3/3 20:31
加载中...