Anagrams by Stack dfs

本文探讨了一个典型深度优先搜索(DFS)题目,该题目巧妙地结合了栈的数据结构。通过具体的代码实现,作者分享了解题思路及过程,旨在帮助读者更好地理解DFS与栈的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
很明显的深搜的题目,而且很用到了栈的知识,不错的题目,
  感觉还不是很懂,有点瓶紧的感觉,应该是对栈不是很熟悉的缘故吧,
  感觉好像做过的dfs的题目好像都有特定的格式一样的,
  好好加油
  */

#include<iostream>
#include<stack>
using namespace std;
char a[1000];
char b[1000];
bool hash[2000];
int lena, lenb;
stack<char> s;

void dfs(int si, int sj, int sk)
{
 int i;
 if(sj == lenb)
 {
  for(i = 0; i < sk; i++)
  /*  @ PE
  if(i != sk - 1)
  {
   if(hash[i])
    cout<<"i"<<" ";
   else
    cout<<"o"<<" ";
  }
  */
  //else
  //{
   if(hash[i])
    cout<<"i"<<" ";
   else
    cout<<"o"<<" ";
  //}
  cout<<endl;
  return ;
 }
 if(si < lena)
 {
  hash[sk] = true;
  s.push(a[si]);
  dfs(si + 1, sj, sk + 1);
  s.pop();
 }
 //if(sj < lenb)
 if(!s.empty() && b[sj] == s.top())
 {
  //if(b[sj] == s.top())
  //{
   char c = s.top();
   s.pop();
   hash[sk] = false;
   dfs(si, sj + 1, sk + 1);
   s.push(c);
  //}
 }
 return;
}
int main()
{

 while(cin>>a>>b)
 {
  lena = strlen(a);
  lenb = strlen(b);
  if(lena != lenb)
  {

   cout<<"["<<endl;
   cout<<"]"<<endl;

  }
  else
  {
   cout<<"["<<endl;
   dfs(0, 0 , 0);
   cout<<"]"<<endl;
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值