问有几种新增航班方法可以去目标岛(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;
}
相关推荐
鹿角片ljp3 分钟前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技16 分钟前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
.道阻且长.3 小时前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq73 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.4 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
小欣加油5 小时前
leetcode3069 将元素分配到两个数组中I
数据结构·c++·算法·leetcode·职场和发展
不会代码的小猴5 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军5 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术6 小时前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent