代码随想录算法训练营 | 图论 | DFS

98. 所有可达路径// DFS

#include 
using namespace std;

vector> result;
vector path;

void dfs(const vector> &graph, int i, int target) {
  if (i == target) {
    result.push_back(path);
    return;
  }
  for (int nums : graph[i]) {
    path.push_back(nums);
    dfs(graph, nums, target);
    path.pop_back();
  }
}

int main() {
  int n, m;
  cin >> n >> m;
  vector> graph(n + 1);
  int temp, next;
  for (int i = 0; i < m; i++) {
    cin >> temp >> next;
    graph[temp].push_back(next);
  }
  path.push_back(1);
  dfs(graph, 1, n);
  if (result.size() == 0)
    cout<<-1<

99. 岛屿数量//。。感觉这题没必要拘泥于用什么搜索。。

#include
using namespace std;


void DFSfindsameIsland(vector>& finded,const vector>& graph,int a,int b){
    if(a<0||b<0||a>graph.size()-1||b>graph[a].size()-1) return;
    else if(graph[a][b]==0) return;
    else if(graph[a][b]==1){
        if(finded[a][b]==false){
            finded[a][b]=true;
            DFSfindsameIsland(finded,graph,a,b+1);
            DFSfindsameIsland(finded,graph,a+1,b);
            DFSfindsameIsland(finded,graph,a,b-1);
            DFSfindsameIsland(finded,graph,a-1,b); 
        }
        else return;
    }
}
int main(){
    int i,j;
    cin>>i>>j;
    vector> graph(i,vector (j));
    for(int a=0;a>graph[a][b];
        }
    }
    vector> finded(i,vector (j,false));
    int result=0;
    for(int a=0;a

100. 岛屿的最大面积//偷懒了。随便拿上一题的代码改改就交了

#include
using namespace std;


int DFSfindsameIsland(vector>& finded,const vector>& graph,int a,int b){
    if(a<0||b<0||a>graph.size()-1||b>graph[a].size()-1) return 0;
    else if(graph[a][b]==0) return 0;
    else{
        if(finded[a][b]==false){
            int result=1;
            finded[a][b]=true;
            result+=DFSfindsameIsland(finded,graph,a,b+1);
            result+=DFSfindsameIsland(finded,graph,a+1,b);
            result+=DFSfindsameIsland(finded,graph,a,b-1);
            result+=DFSfindsameIsland(finded,graph,a-1,b);
            return result;
        }
        else return 0;
    }
}
int main(){
    int i,j;
    cin>>i>>j;
    vector> graph(i,vector (j));
    for(int a=0;a>graph[a][b];
        }
    }
    vector> finded(i,vector (j,false));
    int result=0;int maxaera=0;
    for(int a=0;a

你可能感兴趣的:(代码随想录学习记录,深度优先,算法,图论)