|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 永远Forever 于 2023-10-26 23:31 编辑
题目如图所示,代码如下,
请帮忙优化一下这个bfs代码,超时了,谢谢各位大佬。
- #include<bits/stdc++.h>
- using namespace std;
- int n;
- int a[2005][2005];
- int vis[2005][2005];
- int d[2005][2005];
- int next_[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };//右下左上
- typedef pair<int, int> PII;
- queue<PII> q;
- int ix, iy;
- int bfs(int x, int y) {
- q.push({ x,y });
- vis[x][y] = 1;
- while (!q.empty()) {
- PII t = q.front();
- q.pop();
- for (int i = 0; i < 4; i++)
- {
- int tx = (t.first + next_[i][0] - 1 + n) % n + 1;
- int ty = (t.second + next_[i][1] - 1 + n) % n + 1;
- if (!vis[tx][ty] && a[tx][ty]) {
- d[tx][ty] = d[t.first][t.second] + 1;//记录步数
- vis[tx][ty] = 1;//记录是否访问过
- q.push({ tx,ty });
- }
- }
- }
- return 0;
- }
- int main() {
- cin >> n;
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= n; j++) {
- cin >> a[i][j];
- if (a[i][j] == 2)
- {
- ix = i;
- iy = j;
- a[i][j] = 0;
- }
- }
- }
- bfs(ix, iy);
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= n; j++) {
- cout << d[i][j] << " ";
- }
- cout << endl;
- }
- return 0;
- }
复制代码
优化代码可以从以下几个方面入手:
1. 避免重复计算:在bfs函数中,每次计算tx和ty时都涉及到了一些复杂的操作,可以将这些操作提到循环外,只计算一次,然后在循环内直接使用计算好的结果。
2. 减少内存使用:在bfs函数中,使用了一个二维数组vis来记录是否访问过某个位置,可以将其优化为一个一维数组,因为每次只需要记录是否访问过,不需要记录具体的访问次数。
3. 减少不必要的操作:在bfs函数中,每次都需要判断a[tx][ty]是否为1,可以提前判断一次,然后在循环内直接使用判断结果。
优化后的代码如下:
- #include<bits/stdc++.h>
- using namespace std;
- int n;
- int a[2005][2005];
- int vis[2005];
- int d[2005][2005];
- int next_[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };//右下左上
- typedef pair<int, int> PII;
- queue<PII> q;
- int ix, iy;
- int bfs(int x, int y) {
- q.push({ x,y });
- vis[x] = 1;
- while (!q.empty()) {
- PII t = q.front();
- q.pop();
- for (int i = 0; i < 4; i++) {
- int tx = (t.first + next_[ i][0] - 1 + n) % n + 1;
- int ty = (t.second + next_[ i][1] - 1 + n) % n + 1;
- if (!vis[tx] && a[tx][ty] == 1) {
- d[tx][ty] = d[t.first][t.second] + 1;//记录步数
- vis[tx] = 1;//记录是否访问过
- q.push({ tx,ty });
- }
- }
- }
- return 0;
- }
- int main() {
- cin >> n;
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= n; j++) {
- cin >> a[ i][j];
- if (a[ i][j] == 2) {
- ix = i;
- iy = j;
- a[ i][j] = 0;
- }
- }
- }
- bfs(ix, iy);
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= n; j++) {
- cout << d[ i][j] << " ";
- }
- cout << endl;
- }
- return 0;
- }
复制代码
优化后的代码将重复计算的部分提到循环外,并使用一维数组vis来记录是否访问过某个位置,减少了内存使用。同时,提前判断a[tx][ty]是否为1,减少了不必要的操作。这些优化可以提高代码的执行效率,避免超时的问题。
|
-
|