问有几种新增航班方法可以去目标岛(gpt对回溯的条件判断不严苛,容易漏)

有n个岛,m班双向航线,航线用x,y表示x和y两个岛之间是有航班的,我要从s岛去t岛,请问是否可以?c++,DFS

输入

3 2 0 2

0 1

1 2

输出

2

c 复制代码
bool dfs(int u, int t, vector<bool>& visited, vector<vector<int>>& adj) {
  // 到达目的地
  if (u == t) {
    return true;
  }

  visited[u] = true;
  for (int v : adj[u]) {
    if (!visited[v]) {
      if (dfs(v, t, visited, adj)) {
          //回溯 1!!!!!!!!!!!!!!!
        visited[u] = false;
        return true;
      }
    }
  }

  // 回溯 2!!!!!!!!!!!!!!!!!!!
  visited[u] = false;
  return false;
}


int main() {
  string str;
  freopen("test.txt","r",stdin);
  int n, m, s, t;
  cin >> n >> m >> s >> t;

  // 构建邻接表
  vector<vector<int>> adj(n);
  for (int i = 0; i < m; i++) {
    int x, y;
    cin >> x >> y;
    adj[x].push_back(y);
    adj[y].push_back(x);
  }

  // 深度优先搜索
  int count = 0;
  int res = 0;
  vector<bool> visited(n, false);
  for (int i = 0; i < n - 1; i++) {
    for(int j = i+1; j < n; j++){
        adj[i].push_back(j);
        adj[j].push_back(i);
        for(auto x : adj){
            for(auto y : x){
                cout << y << " ";
            }
            cout <<endl;
        }

        if(dfs(s, t, visited, adj)){
            cout <<" succeed" <<endl;
            cout << "i = " <<i <<endl;
            cout << "j = " <<j <<endl;
            res++;
        }
        cout <<"-------"<<endl;
        adj[i].pop_back();
        adj[j].pop_back();
    }
  }


  // 输出结果
  cout << res << endl;

  return 0;
}
相关推荐
LYFlied19 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠19 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
ytttr87320 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
jianfeng_zhu1 天前
整数数组匹配
数据结构·c++·算法
smj2302_796826521 天前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied1 天前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-1 天前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄1 天前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
百***07451 天前
GPT-Image-1.5 极速接入全流程及关键要点
人工智能·gpt·计算机视觉
来深圳1 天前
leetcode 739. 每日温度
java·算法·leetcode