JustPaste
HomeCategoriesAboutDonateContactTerms of UsePrivacy Policy
JustPaste

Free online notepad — write and share instantly

Navigate

  • Home
  • Timeline
  • Categories

Info

  • About
  • Donate
  • Contact

Legal

  • Terms of Use
  • Privacy Policy

© 2026 JustPaste.app. All rights reserved.

Made with ♥ by JustPaste

Untitled Page | JustPaste.app
8 days ago1 views
👨‍💻Programming

Untitled Page

#include <stdio.h>

#define MAX 100

int graph[MAX][MAX];
int visited[MAX];
int stack[MAX];
int n;

void DFS(int vertex) {
	int top = -1;
	stack[++top] = vertex;
	
	while (top > -1) {
		vertex = stack[top--];
		if (visited[vertex]) {
			continue;
		}
		
		visited[vertex] = 1;
		printf("%d ", vertex);
		
		int i;
		for (i = 0; i < n; i++) {
			if (graph[vertex][i] == 1 && !visited[i]) {
				stack[++top] = i;
			}
		}
	}
	
//	visited[vertex] = 1;
//	printf("%d ", vertex);
//	
//	int i;
//	for (i = 0; i < n; i++) {
//		if (graph[vertex][i] == 1 && !visited[i]) {
//			DFS(i);
//		}
//	}
}

int main() {
	int u, v, edges, start;
	printf("Enter number of vertices: ");
	scanf("%d", &n);
	
//	printf("Enter number of edges: ");
//	scanf("%d", &edges);
	
	int i, j;
	for (i = 0; i < n; i++) {
		int edges;
		printf("Enter number of edges for %d: ", i);
		scanf("%d", &edges);
		printf("Enter edges for %d: ", i);
		for (j = 0; j < edges; j++) {
			int edge;
			scanf("%d", &edge);
			graph[i][edge] = 1;
		}
	}
	
//	int i;
//	printf("Enter edges (u v): \n");
//	for (i = 0; i < edges; i++) {
//		scanf("%d %d", &u, &v);
//		graph[u][v] = 1;
//		graph[v][u] = 1;
//	}
	
	printf("Enter starting vertex: ");
	scanf("%d", &start);
	
	DFS(start);
	printf("\n");
	
	return 0;
}
← Back to timeline