问有几种新增航班方法可以去目标岛(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;
}
相关推荐
yyy(十一月限定版)44 分钟前
寒假集训4——二分排序
算法
星火开发设计1 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
醉颜凉1 小时前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐1 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗1 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
User_芊芊君子1 小时前
【LeetCode经典题解】搞定二叉树最近公共祖先:递归法+栈存路径法,附代码实现
算法·leetcode·职场和发展
算法_小学生1 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
执着2591 小时前
力扣hot100 - 234、回文链表
算法·leetcode·链表
Gorgous—l1 小时前
数据结构算法学习:LeetCode热题100-多维动态规划篇(不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离)
数据结构·学习·算法
熬夜造bug1 小时前
LeetCode Hot100 刷题路线(Python版)
算法·leetcode·职场和发展