0
点赞
收藏
分享

微信扫一扫

【C++庖丁解牛】高阶数据结构---红黑树详解(万字超详细全面介绍红黑树)

三次方 04-10 13:30 阅读 1

蓝桥杯练习笔记(十八)

一、用辅助栈来优化递归深度过大的问题

在这里插入图片描述

  • 输入示例
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;
}

举报

相关推荐

0 条评论