-
Notifications
You must be signed in to change notification settings - Fork 0
/
distributed_tasks.cpp
83 lines (70 loc) · 1.77 KB
/
distributed_tasks.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <mpi.h>
#include <iostream>
#include <vector>
#include <chrono>
#include <cstdlib>
using namespace std;
using namespace chrono;
int isSafe(int *board, int row, int col, int N)
{
for (int i = 0; i < col; i++)
{
if (board[i] == row || abs(board[i] - row) == col - i)
{
return false;
}
}
return true;
}
int solveNQueensUtil(int *board, int col, int N)
{
if (col == N)
{
return 1; // Found one solution
}
int count = 0;
for (int i = 0; i < N; i++)
{
if (isSafe(board, i, col, N))
{
board[col] = i;
count += solveNQueensUtil(board, col + 1, N);
}
}
return count;
}
int main(int argc, char *argv[])
{
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int N = 14; // Default board size
if (argc > 1)
{
N = atoi(argv[1]);
}
int *board = new int[N];
int global_count = 0;
auto start = high_resolution_clock::now();
// Divide the first row choices among nodes
int local_count = 0;
for (int i = rank; i < N; i += size)
{
board[0] = i;
local_count += solveNQueensUtil(board, 1, N);
}
// Reduce all local counts to global count
MPI_Reduce(&local_count, &global_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
if (rank == 0)
{
cout << "Number of queens: " << N << endl;
cout << "Total solutions found: " << global_count << endl;
cout << "Execution time: " << duration.count() << " microseconds" << endl;
}
delete[] board;
MPI_Finalize();
return 0;
}