sdut 图的深度遍历
生活随笔
收集整理的這篇文章主要介紹了
sdut 图的深度遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
圖的深度遍歷
Time Limit:?1000MS?Memory Limit:?65536KB Submit?Statistic?DiscussProblem Description
請定一個無向圖,頂點編號從0到n-1,用深度優先搜索(DFS),遍歷并輸出。遍歷時,先遍歷節點編號小的。Input
輸入第一行為整數n(0 < n < 100),表示數據的組數。 對于每組數據,第一行是兩個整數k,m(0 < k < 100,0 < m < k*k),表示有m條邊,k個頂點。 下面的m行,每行是空格隔開的兩個整數u,v,表示一條連接u,v頂點的無向邊。Output
輸出有n行,對應n組輸出,每行為用空格隔開的k個整數,對應一組數據,表示DFS的遍歷結果。Example Input
1 4 4 0 1 0 2 0 3 2 3Example Output
0 1 2 3#include<iostream> #include<cstring> using namespace std; int map[100][100],path[10000],visit[10000]={0},l=1,n,m; void DFS(int st,int ed) {/*if(st==ed){for(int i=0;i<l-1;++i)cout<<path[i]<<' ';cout<<path[l-1]<<endl;}*/visit[st]=1;//標記已經訪問過 for(int i=0;i<n;++i){if(!visit[i]&&map[st][i]){cout<<' '<<i; DFS(i,n-1);//--l;//visit[i]=0;//記憶化搜索 }} } int main() {int t;cin>>t;while(t--){memset(visit,0,sizeof(visit));memset(map, 0, sizeof(map)); cin>>n>>m;for(int i=0;i<m;++i){int a,b;cin>>a>>b;map[a][b]=map[b][a]=1;}cout<<0;DFS(0,n-1);cout<<endl; }return 0; }2018/03/25更新java代碼public class Main {private static int[][] go = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; // 上下左右public static int m = 0, n = 0, s = 0;private static int[][] vis = new int[10][10];public static void main(String[] args) {int N;Scanner sc = new Scanner(System.in);N = sc.nextInt();for (int i = 0; i < N; i++) {init();m = sc.nextInt();n = sc.nextInt();int[][] a = new int[m][n];for (int i1 = 0; i1 < m; i1++) {for (int j = 0; j < n; j++) {a[i1][j] = sc.nextInt();}}dfs(a, 0, 0);System.out.println(s);s = 0;}}private static void init() {for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {vis[i][j] = 0;}}}private static void dfs(int[][] a, int x, int y) {if (x == m - 1 && y == n - 1) {s++;return;} else { for (int i = 0; i < 4; i++) {int xx = x + go[i][0];int yy = y + go[i][1];if (xx >= 0 && xx < m && yy >= 0 && yy < n && vis[xx][yy] ==0 && a[xx][yy]==0) { x = xx;y = yy;System.out.println("x:"+x+"--"+"y:"+y);vis[x][y] = 1;dfs(a, x, y);System.out.println("yes I do "+x+'-'+y);vis[x][y] = 0;}}}} }
總結
以上是生活随笔為你收集整理的sdut 图的深度遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html之属性的应用
- 下一篇: 中国剩余定理(模板+代码)