You are on page 1of 9

1, DFS

1.1 Code

#include <bits/stdc++.h>

using namespace std;

int n, u;

int a[1000][1000];

bool chuaXet[1000];

void DFS(int u) {

std::stack<int> Stack;

Stack.push(u);

chuaXet[u] = false;

cout<<u<<" ";

while (!Stack.empty()) {

int s = Stack.top(); Stack.pop();

for (int i = 1; i <= n; i++) {

if(a[s][i] == 1 && chuaXet[i] == true) {

chuaXet[i] = false;

cout<<i<<" ";

Stack.push(s);

Stack.push(i);

break;

}
void reInit() {

for (int i = 1; i <= n; i++)

chuaXet[i] = true;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

a[i][j] = 0;

int main() {

cout << "Nhap so dinh cua do thi: ";

cin >> n;

cout << "Nhap ma tran ke cua do thi: \n";

reInit();

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

cin >> a[i][j];

cout << "Nhap dinh bat dau duyet DFS: ";

cin >> u;

DFS(u);

return 0;

}
1.2 Test 1
0111000000000
1011010000000
1101100000000
1110001000000
0010011100010
0100101000010
0001110100000
0000101000010
0000000001101
0000000010111
0000000011001
0000110101000
0000000011100

1.3 Test 2
0111000000
1001100000
1001010000
1110110010
0101000100
0011001000
0000010011
0000100011
0001001101
0000001110

1.4 Test 3
0110
1000
1001
0010
2, BFS
2.1 Code
#include <bits/stdc++.h>

using namespace std;

int n, u;

int a[1000][1000];

bool chuaXet[1000];

void BFS(int u) {

std::queue<int> Queue;

Queue.push(u);

chuaXet[u] = false;

while(!Queue.empty()) {

int s = Queue.front(); Queue.pop();

cout<<s<<" ";

for(int i = 1; i <= n; i++) {

if(a[s][i] == 1 && chuaXet[i] == true) {

Queue.push(i);

chuaXet[i] = false;

void reInit() {

for (int i = 1; i <= n; i++)

chuaXet[i] = true;
for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

a[i][j] = 0;

int main() {

cout << "Nhap so dinh cua do thi: ";

cin >> n;

cout << "Nhap ma tran ke cua do thi: \n";

reInit();

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

cin >> a[i][j];

cout << "Nhap dinh bat dau duyet DFS: ";

cin >> u;

BFS(u);

return 0;

2.2 Test 1
0111000000000
1011010000000
1101100000000
1110001000000
0010011100010
0100101000010
0001110100000
0000101000010
0000000001101
0000000010111
0000000011001
0000110101000
0000000011100

2.3 Test 2
0111000000
1001100000
1001010000
1110110010
0101000100
0011001000
0000010011
0000100011
0001001101
0000001110

2.4 Test 3

01100
10001
10010
00100
01000

You might also like