蓝桥杯练习笔记(十八)
一、用辅助栈来优化递归深度过大的问题
- 输入示例
0000100010000001101010101001001100000011
0101111001111101110111100000101010011111
1000010000011101010110000000001011010100
0110101010110000000101100100000101001001
0000011010100000111111001101100010101001
0110000110000000110100000000010010100011
0100110010000110000000100010000101110000
0010011010100110001111001101100110100010
1111000111101000001110010001001011101101
0011110100011000000001101001101110100001
0000000101011000010011111001010011011100
0000100000011001000100101000111011101100
0010110000001000001010100011000010100011
0110110000100011011010011010001101011011
0000100100000001010000101100000000000010
0011001000001000000010011001100101000110
1110101000011000000100011001001100111010
0000100100111000001101001000001010010001
0100010010000110100001100000110111110101
1000001001100010011001111101011001110001
0000000010100101000000111100110010101101
0010110101001100000100000010000010110011
0000011101001001000111011000100111010100
0010001100100000011000101011000000010101
1001111010010110011010101110000000101110
0110011101000010100001000101001001100010
1101000000010010011001000100110010000101
1001100010100010000100000101111111111100
1001011010101100001000000011000110110000
0011000100011000010111101000101110110001
- 这是我一开始写的dfs搜索与第一行相连的0的个数(占用内存过大):
#include <iostream>
#include<bits/stdc++.h>
using namespace std;vector<string> a;
int cnt=0;void dfs(int n,int m)
{if(n<0||m<0||n>29||m>39){return;}if(a[n][m]=='1'||a[n][m]=='2')return;if(a[n][m]=='0'){cnt++;a[n][m]='2';}dfs(n-1,m);//纵向dfs(n+1,m);dfs(n,m-1);dfs(n,m+1);
}int main()
{// 请在此输入您的代码for(int i=0;i<40;i++){string s;cin>>s;a.push_back(s);}for(int i=0;i<10;i++){dfs(0,i);//横向}
cout<<cnt;return 0;
}
- 然后gpt给出了优化意见:用辅助栈去代替递归的过程
在你提供的代码中,出现了内存超限的问题。这是因为你使用的递归深度过大,导致栈空间不足以容纳如此多的函数调用。
对于这个问题,一种解决方法是将递归改为迭代,使用循环来实现深度优先搜索。通过使用一个辅助栈来模拟递归的过程,可以避免递归深度过大导致的栈溢出。
以下是修改后的代码示例:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;vector<string> a;
int cnt = 0;void dfs(int n, int m)
{stack<pair<int, int>> st;st.push(make_pair(n, m));while (!st.empty()){int x = st.top().first;int y = st.top().second;st.pop();if (x < 0 || y < 0 || x >= 30 || y >= 40){continue;}if (a[x][y] == '1' || a[x][y] == '2'){continue;}if (a[x][y] == '0'){cnt++;a[x][y] = '2';}st.push(make_pair(x - 1, y)); // 向上st.push(make_pair(x + 1, y)); // 向下st.push(make_pair(x, y - 1)); // 向左st.push(make_pair(x, y + 1)); // 向右}
}int main()
{// 请在此输入您的代码for (int i = 0; i < 40; i++){string s;cin >> s;a.push_back(s);}for (int i = 0; i < 10; i++){dfs(0, i); // 横向}cout << cnt;return 0;
}
这里的思想是递归本身也是利用了栈去维护自己递归信息。所以直接在dfs函数里就用一个栈来模拟函数的递归。