简单bfs题,但我的程序的输出结果问题困扰我好久了

UVA439 Knight Moves

@[LukeSu](/user/593753) ```cpp #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; } ```
by LukeSu @ 2022-03-04 11:54:58


@[LukeSu](/user/593753) ``` while(scanf("%c%d %c%d", &ch1, &temp1, &ch2, &temp2) != EOF){ ``` 可以改成 ``` while(scanf("%c%d %c%d\r\n", &ch1, &temp1, &ch2, &temp2) != EOF){ ``` 然后在cout最后加上\n
by 编码落寞 @ 2022-03-04 12:52:35


@[编码落寞](/user/557751) 按你的方法第一行输入数据读不进去。。
by LukeSu @ 2022-03-04 20:26:56


@[LukeSu](/user/593753) 你在洛谷IDE上试,因为\r\n是linux下换行符
by 编码落寞 @ 2022-03-07 10:49:59


@[编码落寞](/user/557751) 问题我解决了! 使用rewind方法放在while里即可,rewind()作用是清空缓存区,这样就可以避免读入多余换行符: ```cpp rewind(stdin); ```
by LukeSu @ 2022-03-07 19:39:05


@[编码落寞](/user/557751) 样例是过了,可是提交完TLE了。。。。(笑哭) 看来我还是得换种思路来解决这道题。总之谢谢你的帮助!
by LukeSu @ 2022-03-07 19:41:24


不知道楼主现在解决这个问题没有,过了好久了( 你可以试试把输入改成 ``` scanf("%c%d %c%d%*c", &ch1, &temp1, &ch2, &temp2) != EOF)``` 我这么改就好了
by Eureka_yzy @ 2022-06-06 22:35:51


|