Related
I have an algorithm that search for a exit of a maze using recursive function , how i pass this to a function without recursive but using stack?What this algorithm do is basically , try to found the exit of a matriz , if the next step is 0 or if has already been covered comeback and try another path, but a i need to change the recursive function to a function using stack instead of recursion how i do that?
void print_maze(char **maze, int width, int height) {
for (int i=0; i<13; i++ ){
for (int j=0; j<10; j++ )
{
printf ("%d", maze[i][j]);
}
printf("\n");
}
}
int maze(int x_current, int y_current,char **mazeHere, int height,int width)
{
if (x_current < 0 || x_current >= width || y_current < 0 || y_current >= height)
return 0;
char here = mazeHere[x_current][y_current];
if (here == 3)
return 1;
if(here == 0 || here == 2)
return 0;
mazeHere[x_current][y_current] = 2;
if(maze(x_current ,y_current-1,mazeHere,height,width))return 1;
if(maze(x_current+1,y_current,mazeHere,height,width))return 1;
if(maze(x_current,y_current+1,mazeHere,height,width))return 1;
if(maze(x_current-1,y_current,mazeHere,height,width))return 1;
else{ mazeHere[x_current][y_current] = 1;
return 0;
}
}
int main(void)
{
char matriz [13][10]={
{0,0,0,0,0,0,0,0,0,0},
{0,0,1,1,1,1,1,0,0,0},
{0,0,1,0,0,0,1,0,0,0},
{0,0,1,0,0,0,1,0,0,0},
{1,1,1,0,1,1,1,1,1,0},
{0,1,0,0,1,0,0,0,0,0},
{0,1,1,0,1,1,1,0,0,0},
{0,0,1,0,1,0,0,0,1,0},
{0,0,1,0,0,0,1,1,1,0},
{0,0,1,1,1,1,1,0,0,0},
{0,0,0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,1,1,1,3},
{0,0,0,0,0,0,0,0,0,0},};
int b= 0;
int height = 10;
int width = 13;
int p = 0;
int o = 0;
char **a = malloc(width * sizeof(char*));
for(int x = 0; x< width; x++){
a[x] = malloc(height * sizeof(char));
}
for (int i=0; i<13; i++ ){
for (int j=0; j<10; j++ )
{
a[i][j]= matriz[i][j];
}
}
int res = maze(4,0,a,height,width);
puts(res ? "success!" : "no luck!");
print_maze(a, width, height);
return 0;
}
I understand it's hard without recursion. By the way, conversion from recursion into using stack is not so hard, if you wrote code of stack data structure and its operation. We are going to pursue the matter on the assume.
Recursive function basically has structure like this:
position *seek(position *now, type arg...){
...
if(condition){
return NULL;
} else {
now->next = seek(arg_next);
}
}
It's OK to understand just with your feeling. What it does here is chaining new result to results until now. In other words, storing results as data structure. Here, data structure changes to stack. Then...:
void seek(stack *stack, type arg...){
...
while(1){
if(condition){
break;
} else {
stack->push(next_result)
}
}
}
It's so easy! All that is left is increasing conditions and considering backtracking. Based on the above, try to rewrite your code!
I am trying to populate a 2D array vertically or horizontally from a given coordinate, if the indexes are in range.
Below is the program I can think about as of now.
I just want to know if there is any other optimized way to perform this logical operation.
public static void Main()
{
var arr = new string[10,10];
int x = 0;
int y = 1;
int len = 5;
string somevalue = "x";
string align = "vertical";
int i = x;
int j = y;
try
{
while(len > 0)
{
arr[i,j] = somevalue;
if(align == "vertical")
j++;
else
i++;
len--;
}
}
catch(IndexOutOfRangeException ex)
{
Console.WriteLine(ex);
}
}
I'm trying to write Conway's game of life in C. This is what I have so far. I'm using pointers to refer to the arrays, which has never caused me problems before, but the function place_cell is causing a segfault.
Here's what I've tried so far:
- I tried making the grid with constants, 100 x 100, and 10 x 10. Modifying
values inside of those constant grids still gives me a segfault.
- I tried using constants for place_cell, still got a segfault.
int** make_grid(int x, int y) {
int** is = (int**)malloc(sizeof(int*) * y);
if(! is) {
fprintf(stderr, "make_grid: malloc failed");
exit(1);
}
int j;
for(j = 0; j < y; j++) {
is[j] = (int*)malloc(sizeof(int) * x);
if(!is[j]) {
fprintf(stderr, "make_grid: malloc failed");
exit(1);
}
}
return is;
}
/* takes two integers and places a cell at those coords */
void place_cell(int** is, int sidex, int sidey, int x, int y) {
if(x >= sidex || y >= sidey) {
fprintf(stderr, "place_cell: out of grid range\n");
exit(1);
}
is[y][x] = 1;
}
int check_surroundings(int** is, int sidex,
int sidey, int x, int y) {
int y_less = y - 1;
if(y == 0) {
y_less = sidey - 1;
}
int y_more = y + 1;
if(y == sidey - 1) {
y_more = 0;
}
int x_less = x - 1;
if(x == 0) {
x_less = sidex - 1;
}
int x_more = x + 1;
if(x == sidex - 1) {
x_more = 0;
}
int p = is[y_less][x_less] +
is[y_less][x] +
is[y_less][x_more] +
is[y][x_less] +
is[y][x_more] +
is[y_more][x_less] +
is[y_more][x_less] +
is[y_more][x_more];
return p;
}
void change_condition(int** is,
int sidex, int sidey, int x, int y) {
int* state = &is[y][x];
int surr = check_surroundings(is, sidex, sidey, x, y);
if(surr > 3) {
*state = 0;
} else if(surr == 3 || surr == 2) {
*state = 1;
} else {
*state = 0;
}
}
void print_grid(int** is, int sidex, int sidey) {
int i, j;
for(i = 0; i < sidey; i++) {
for(j = 0; j < sidex; j++) {
if(is[i][j] == 1) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
}
void new_generation(int** is, int sidex, int sidey) {
int i, j;
for(i = 0; i < sidey; i++) {
for(j = 0; j < sidex; j++) {
change_condition(is, sidex, sidey, j, i);
}
}
}
void play(int** is, int sidex, int sidey) {
int i = 0;
while(i < 100) {
new_generation(is, sidex, sidey);
print_grid(is, sidex, sidey);
i++;
}
}
here's my main:
int main(int argc, char* argv[]) {
int sidex = atoi(argv[0]);
int sidey = atoi(argv[1]);
int** is = make_grid(10, 10);
int i;
for(i = 2; i < argc; i += 2) {
place_cell(is, sidex, sidey,
atoi(argv[i]), atoi(argv[i + 1]));
}
return 0;
}
edit:
int** make_grid(int x, int y) {
int (*is)[x] = (int*)malloc(sizeof(int) * y * x);
if(! is) {
fprintf(stderr, "make_grid: malloc failed");
exit(1);
}
int j;
for(j = 0; j < y; j++) {
is[j] = (int*)malloc(sizeof(int) * x);
if(!is[j]) {
fprintf(stderr, "make_grid: malloc failed");
exit(1);
}
}
return is;
}
This isn't right at all but I can't put my finger on why. Can someone explain to me what to change like I'm five? (a five year-old who knows C, I guess)
I just copied your entire code and tried to run the program. The memory access violation (at least for me) is in this line:
int sidex = atoi(argv[0]);
int sidey = atoi(argv[1]); <-- memory access violation
The reason is (in my case at least) that I just ran the program with no arguments.
Now, even if I did provide the arguments on the command line the indexing is still off. The first argument argv[0] is the name of the executable, not the first argument after the name.
So, a few things to note for your code:
It is not guaranteed that there will be arguments. You should always check the argc to make sure you can index into argv
Those arguments are not guaranteed to be integer numbers either - you better check for that too, before you use them as your dimensions
Of course with the indexing shift you should adjust for your "array reading" code accordingly as well. But once you fix the indexing this should be an easy one for you
You are not declaring a two-dimensional array with that syntax, so the memory is not aligned the way you think, thus a segmentation fault. Declaring a pointer int** does not make it a 2-D array. (Surely you don't think int *** would get you a data cube ?).
Heap allocate a 2D array (not array of pointers)
One of the comments above gives the other problem, the zero parameter to a C program argv[0] is the name of the program, not the first parameter on the command line, that is argv[1].
I have a 3D matrix mat[100][100][100]. What is the efficient way to find a row with same elements that appears in mat[0][][], mat[1][][],....,mat[99][][]?
A simple approach would be comparing each row of mat[0][][] to all rows of the remaining 99 matrices, but it wouldn't be very efficient(I guess). Is there a better way to do it?
To expand on the comment by #chux, the first step is to compute a hash value for each row of each matrix. That's 10000 hash values in all. The results should be stored in an array of 10000 structs.
struct info
{
int m; // the matrix number
int row; // the row number
uint32_t hash; // the hash value for mat[m][row]
};
static struct info hashArray[10000];
After filling in all 10000 entries of the hashArray, sort the array by hash value. Then you can simply scan the array to find any duplicate hash values. When you do find duplicates, you need to confirm by comparing the row elements.
I finally found some time to write the content addressable code. It turns out to be much faster than using hash tables. But the catch is that the code is way more complex and the program takes WAY more memory. My final opinion is that unless you really need the extra speed, stick with the hash table.
Some examples of test runs are given below. The argument to the program specify the number of unique rows. The program fills the rest with randomly chosen existing rows. Then the rows are shuffled. The program looks for all duplicate rows and reports the number of duplicate rows and the time it took for both hash and content addressable tables.
bing#mint5 ~ $ cc -O2 cattest.c -o cattest
bing#mint5 ~ $ ./cattest 500
CAT Test 9500 0.0083
Hash Test 9500 0.0499
bing#mint5 ~ $ ./cattest 5000
CAT Test 5000 0.0195
Hash Test 5000 0.1477
bing#mint5 ~ $ ./cattest 9000
CAT Test 1000 0.0321
Hash Test 1000 0.1092
/* content addressable table vs hash table */
/* written by Bing H Bang */
/* I DONOT give permission to any snot-nosed students to copy my work and turn it in
as their own */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <sys/sysinfo.h>
double etime()
{
struct timeval tv;
double dt, df;
gettimeofday(&tv, NULL);
dt = (double)(tv.tv_sec);
df = ((double)(tv.tv_usec))/1000000.0;
return(dt+df);
}
struct CAT_entry
{
unsigned fval;
unsigned short rows[10000];
unsigned short num;
unsigned short used;
struct CAT_entry *next;
} *CAT[256] = {NULL};
struct CAT_entry stmem[10000];
int stidx = 0;
unsigned dat[100][10000];
char map[10000];
unsigned hasht[10000];
#define highbit (1 << ((sizeof(unsigned)*8)-1))
unsigned
rotxor(unsigned sum, unsigned v)
{
if((sum & highbit) == 0)
return ((sum << 1) ^ v);
else
return (((sum << 1) | 1) ^ v);
}
unsigned
compute_hash(int y)
{
int x;
unsigned sum = 0;
for(x = 0; x < 100; ++x)
sum = rotxor(sum, dat[x][y]);
return sum;
}
void
mk_hasht()
{
int y;
for(y = 0; y < 10000; ++y)
hasht[y] = compute_hash(y);
}
clearmap()
{
memset((void *)map, 0, 10000);
}
comprow(int y, int yd)
{
int x;
for(x = 0; x < 100; ++x)
if(dat[x][y] != dat[x][yd])
return 0;
return 1;
}
struct CAT_entry **
srch_CAT(unsigned value)
{
struct CAT_entry **p = &(CAT[value&255]);
static struct CAT_entry *r = NULL;
while(*p != NULL)
{
if((*p)->fval == value)
break;
if((*p)->fval > value)
return &r;
else
p = &((*p)->next);
}
return p;
}
void
add_entry(int y, unsigned value)
{
struct CAT_entry **p = &(CAT[value&255]), *q;
while(*p != NULL)
{
q = *p;
if(q->fval == value)
{
q->rows[q->num] = y;
q->num++;
return;
}
if(q->fval > value)
break;
p = &(q->next);
}
q = *p;
//*p = malloc(sizeof(struct CAT_entry));
*p = &stmem[stidx++];
(*p)->next = q;
q = *p;
q->fval = value;
q->num = 0;
q->used = 0;
}
void
mk_CAT()
{
int x,y;
struct CAT_entry **p, *q;
for(y = 0; y < 10000; y++)
add_entry(y, dat[0][y]);
for(x=0; x < 256; ++x)
{
p = &(CAT[x]);
while(*p != NULL)
{
q = *p;
if(q->num == 0)
{
*p = q->next;
//free(q);
}
else
p = &(q->next);
}
}
}
void
gen_data(int npat)
{
int x, y, rnum, limit;
unsigned r;
srandom(time(NULL));
rnum = npat * 100;
for(y = 0; y < rnum; ++y)
dat[y%100][y/100] = random();
for(y = npat; y < 10000; ++y)
{
rnum = random() % npat;
for(x = 0; x < 100; ++x)
dat[x][y]=dat[x][rnum];
}
for(y = 0; y < 10000; ++y)
{
rnum = random() % 10000;
if(rnum == y)
continue;
for(x = 0; x < 100; ++x)
{
r = dat[x][y];
dat[x][y]=dat[x][rnum];
dat[x][rnum] = r;
}
}
}
int
do_CATtest()
{
int y, yd, count = 0, i;
struct CAT_entry **p, *q;
mk_CAT();
clearmap();
for(y = 0; y < 9999; ++y)
{
if(map[y] == 0)
{
map[y] = 1;
if(*(p = srch_CAT(dat[0][y])) != NULL)
{
for(q = *p, i = 0; i < q->num; ++i)
{
yd = q->rows[i];
if(map[yd] == 0)
{
if(comprow(y, yd))
{
map[yd] = 1;
++count;
q->used++;
}
}
}
if(q->num <= q->used)
*p = q->next;
}
}
}
return count;
}
int
do_hashtest()
{
unsigned h;
int x, y, yd, count = 0;
mk_hasht();
clearmap();
for(y = 0; y < 9999; ++y)
{
if(map[y] != 0)
continue;
map[y] = 1;
h = hasht[y];
for(yd = y+1; yd < 10000; ++yd)
{
if(map[yd] != 0)
continue;
if(h == hasht[yd])
if(comprow(y, yd))
{
map[yd] = 1;
++count;
}
}
}
return count;
}
main(int c, char *v[])
{
int npat = 0, count;
double t1, t2;
if(c == 2)
npat = atoi(v[1]);
if(npat <= 0 || npat >= 10000)
{
puts("input param error");
exit(1);
}
gen_data(npat);
npat = 10000 - npat;
t1 = etime();
if((count = do_CATtest()) != npat)
{
printf("CAT test error, %d matches found, not %d", count, npat);
exit(1);
}
t2 = etime();
printf("CAT Test %d %.4f\n", npat, t2-t1);
t1 = etime();
if((count = do_hashtest()) != npat)
{
printf("hash test error, %d matches found, not %d", count, npat);
exit(1);
}
t2 = etime();
printf("Hash Test %d %.4f\n", npat, t2-t1);
}
Make a content addressable table of the first values in each row. Then go through each row, take the first value and look it up on the table. If the lookup returns multiple rows, then those rows should be checked for a match. The searched rows should be remembered as to increase efficiency because the checked rows need not be checked again. You'll end up with a list of identical row groupings.
I try to implement the karger Minimum Cut algorithm (Karger wiki page)
So far, I have tried my algorithm on small examples (input of size 10) and it seems to work. But when I try to have a bigger input, let's say 200. It just crashes.
To store the minimum cut data, I create a 2D array: GraphCut[SIZE_ARRAY][SIZE_ARRAY_2]
SIZE_ARRAY = 200 in this case, but I can't find a good length for SIZE_ARRAY_2.
Issue is, SIZE_ARRAY_2 has to be big as I modify the initial array to merge the different vertices.
If I declare SIZE_ARRAY_2 = 200, the size won't be enough, but if i put SIZE_ARRAY_2 = 1000, the program just crashes.
The thing is, I have to execute the algorithm 100000 times.
Here is parts of the code:
#define ARRAY_SIZE 200
#define ARRAY_SIZE_2 200
int main()
{
int minCut,minMinCut;
for (int k = 0; k < ARRAY_SIZE * ARRAY_SIZE * 4;k++) {
minCut = kargerMinCut(k);
if (k == 0)
minMinCut = minCut;
else if (minMinCut > minCut)
minMinCut = minCut;
}
printf("\n minMinCut = %d\n", minMinCut);
return 0;
}
int kargerMinCut(int k) {
// 1st dimension: each different node
// 2nd dimension: vertices
long graphCut[ARRAY_SIZE + 1][ARRAY_SIZE_2] = {0};
populateIntegerArray(graphCut); // import data from a file
int nodeToMain[ARRAY_SIZE + 1];
int sizeOfMainNode, indexToMerge,initialRand,i,j,m,nodeToMerge,nodeRemaining = ARRAY_SIZE;
for (m = 0;m<ARRAY_SIZE + 1;m++) // initialization of nodeToMain
nodeToMain[m] = m;
while (nodeRemaining > 2) {
i = 0;
j = 0;
srand(time(NULL) + nodeRemaining);// initialise rand
initialRand = nodeToMain[rand()%(ARRAY_SIZE) + 1]; // pick a random initial node, but not a merged one
sizeOfMainNode = sizeOfArray(graphCut[initialRand]); // size of the initial node
srand(time(NULL) + k); // initialise rand
indexToMerge = rand()%sizeOfMainNode;// pick another random node in the linked nodes (its index to be precise)
nodeToMerge = nodeToMain[graphCut[initialRand][indexToMerge]];
for (m = 0;m<ARRAY_SIZE + 1;m++) // update the nodeToMain array, initialRand is now the main node for nodeToMerge
if (nodeToMain[m] == nodeToMerge)
nodeToMain[m] = initialRand;
// remove the nodeToMerge numbers from the graphCut[initialRand] (as they are going to be merged)
while(graphCut[initialRand][j] > 0 && j < sizeOfMainNode) {
if (initialRand == nodeToMain[graphCut[initialRand][j]]) {
// if this is the last element, do nothing
while(nodeToMain[graphCut[initialRand][sizeOfMainNode - 1]] == initialRand && j < sizeOfMainNode - 1) {
graphCut[initialRand][sizeOfMainNode - 1] = 0;
sizeOfMainNode--;
}
graphCut[initialRand][j] = nodeToMain[graphCut[initialRand][sizeOfMainNode - 1]];
graphCut[initialRand][sizeOfMainNode - 1] = 0;
sizeOfMainNode--;
}
j++;
}
i = 0;
while (graphCut[nodeToMerge][i] > 0 && sizeOfMainNode < ARRAY_SIZE_2 && i < ARRAY_SIZE_2) { // add each vextex of the nodeTomerge to the merged nodes
if (nodeToMain[graphCut[nodeToMerge][i]] != initialRand) {
graphCut[initialRand][sizeOfMainNode] = nodeToMain[graphCut[nodeToMerge][i]];
sizeOfMainNode++;
}
i++;
}
nodeRemaining--;
}
return sizeOfArray(graphCut[nodeToMain[1]]);
}
I'm sure that the code is not really clean, maybe even really bad (beginner in C). So i Welcome any other advice.
The errors I get with the debugger seems really random.
Error is:
Impossible to divide by 0
it stops in time64.c at line 62
tim = (__time64_t)((nt_time.ft_scalar - EPOCH_BIAS) / 10000000i64);
The change in array size is probably causing a stack overflow. A common default size for the stack is 1MB (1048576 bytes). If you have:
long graphCut[200][1000];
and 4 == sizeof(long) the graphCut array is taking up 200 * 1000 * 4 = 800000 bytes, which leaves 248576 bytes which may not be enough for the stack variables in populateIntegerArray() function (I don't see that function). If 8 == sizeof(long) then the array would require 1600000 bytes, which is greater than 1MB.
If an array of that size is required then allocate (all or part) on the heap instead of the stack. For example:
long* graphCut[ARRAY_SIZE_1];
int i;
for (i = 0; i < sizeof(graphCut)/sizeof(graphCut[0]); i++)
{
graphCut[i] = malloc(ARRAY_SIZE_2 * sizeof(graphCut[0][0]));
memset(graphCut[i], 0, ARRAY_SIZE_2 * sizeof(graphCut[0][0]));
}
for (i = 0; i < sizeof(graphCut)/sizeof(graphCut[0]); i++)
{
free(graphCut[i]);
}
Some possible problems are integer or stack overflow (so you're on the right site) and memory initialization.
This implementation should allocate graphCut on the heap, and zero it every time kargerMin gets called, thus addressing those problems.
int minCut, minMinCut;
// There is a small possibility that ARRAY_SIZE*ARRAY_SIZE*4 exceeds int boundary if 16-bit
long k;
long **buffer;
// Allocate graphCut on the heap
buffer = malloc((ARRAY_SIZE + 1)*sizeof(long *));
for (k = 0; k < ARRAY_SIZE + 1; k++)
buffer[k] = malloc(ARRAY_SIZE_2*sizeof(long));
for (k = 0; k < ARRAY_SIZE * ARRAY_SIZE * 4;k++) {
minCut = kargerMinCut(k, buffer);
if (k == 0)
minMinCut = minCut;
else if (minMinCut > minCut)
minMinCut = minCut;
}
printf("\n minMinCut = %d\n", minMinCut);
// Here we free the buffer. We could do it in any order, but
// as it costs nothing here to do so, we free it in reverse-
// allocation-order to avoid any possible memory fragmentation
// - which is moot anyway, if this is a main() and we're exiting
// the program. In other instances it could be relevant.
for (k = 0; k < ARRAY_SIZE + 1; k++)
{
free(buffer[ARRAY_SIZE-k]); buffer[ARRAY_SIZE-k] = NULL;
}
free(buffer); buffer = NULL;
// The NULLing of the just-freed variables has no purpose except
// to GUARANTEE that any illegal use of them, dangling pointers,
// leftover copies etc. will immediately trigger a core dump and
// be discovered, instead of lurking undetected.
return 0;
}
int kargerMinCut(long k, long **graphCut) {
// 1st dimension: each different node
// 2nd dimension: vertices
// Zero graphCut. If populateIntegerArray rewrites
// the whole of graphCut, these four lines are redundant.
int i, j;
for (i = 0; i < ARRAY_SIZE + 1; i++)
for (j = 0; j < ARRAY_SIZE_2; j++)
graphCut[i][j] = 0;
// otherwise, they make sure that no old value of graphCut
// or uninitialised value is going to linger and potentially
// corrupt calculations later on.
populateIntegerArray(graphCut); // import data from a file
I have implemented the Karger algorithm in C++. My code below works on large files but I have not optimized enough...it still runs fast though..but could be faster..Try this solution.
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <list>
#include <fstream>
#include <sstream>
#include <set>
#include <stdlib.h>
#include <time.h>
int pick_edge(std::map <int, std::list<int>> g2, set<int> myset, int &u, int &v)
{
std::map <int, std::list<int>>::iterator it;
std::list<int> eachRow;
int rand_vertex;
int rand_edge;
srand (time(NULL));
rand_vertex = (rand() + 1) % myset.size() ;
if (rand_vertex == 0)
rand_vertex = 1;
u = get_value_at_i(myset, rand_vertex);
for (it = g2.begin(); it != g2.end(); ++it) {
if (it->first == u) {
eachRow = it->second;
rand_edge = (rand() + 1) % eachRow.size();
if (rand_edge == 0)
rand_edge = 1;
v = get_edge_at_j(eachRow, rand_edge);
break;
}
}
return 0;
}
map <int, std::list<int>> merge_uv(map <int, std::list<int>> g2, int u, int v)
{
std::map <int, std::list<int>>::iterator it_g;
std::map <int, std::list<int>>::iterator it_u;
std::map <int, std::list<int>>::iterator it_v;
std::list<int>::iterator iter_l;
std::list<int> eachRow, uRow, vRow;
std::list<int> newRow;
int vertex;
int j = 0;
map <int, std::list<int>> new_Graph_G;
vRow.clear();
uRow.clear();
eachRow.clear();
newRow.clear();
for (it_g = g2.begin(); it_g != g2.end(); ++it_g) {
vertex = it_g->first;
eachRow = it_g->second;
if (vertex == u) {
uRow = it_g->second;
it_u = it_g;
j++;
continue;
}
if (vertex == v) {
vRow = it_g->second;
it_v = it_g;
j++;
continue;
}
}
if (j == 2) {
uRow.sort();
vRow.sort();
// uRow.merge(vRow);
for (std::list<int>::iterator ite = vRow.begin(); ite != vRow.end(); ++ite) {
if (*ite != u) {
uRow.push_back(*ite);
}
}
g2.erase(v);
g2[u] = uRow;
}
for (it_g = g2.begin(); it_g != g2.end(); ++it_g) {
eachRow = it_g->second;
for (std::list<int>::iterator ite = eachRow.begin(); ite != eachRow.end(); ++ite) {
if (*ite == v && *ite != it_g->first) {
newRow.push_back(u);
} else if (*ite == it_g->first) {
continue;
} else {
newRow.push_back(*ite);
}
}
new_Graph_G[it_g->first] = newRow;
newRow.clear();
}
for (it_g = g2.begin(); it_g != g2.end(); ++it_g) {
eachRow = it_g->second;
if (it_g->first == u) {
for (std::list<int>::iterator ite = eachRow.begin(); ite != eachRow.end(); ++ite) {
if (*ite != u && *ite != v) {
newRow.push_back(*ite);
}
}
new_Graph_G[it_g->first] = newRow;
break;
}
}
return new_Graph_G;
}
int get_min_cut(std::map <int, std::list<int>> g1)
{
int v;
std::list<int> eachRow;
std::map <int, std::list<int>>::iterator it_g;
int min_cut = 0;
for (it_g = g1.begin(); it_g != g1.end(); ++it_g) {
eachRow = it_g->second;
v = it_g->first;
for (std::list<int>::iterator ite = eachRow.begin(); ite != eachRow.end(); ++ite) {
if (*ite != v) {
min_cut++;
}
}
break;
}
return min_cut;
}
int EdgeContractionAlgorithm()
{
std::map <int, std::list<int>>::iterator it;
int min_cut = 0;
int vertex = 1;
std::list<int> eachRow;
std::set<int> myset;
std::set<int>::iterator itSet;
std::map <int, std::list<int>> g2;
int edge;
int n_vertices;
int cnt = 0;
int u, v;
n_vertices = Cal_nVertices(myset, Graph_G);
g2 = Graph_G;
// Contraction algorithm.
while (n_vertices > 2) {
edge = pick_edge(g2, myset, u, v);
g2 = merge_uv(Graph_G, u, v);
n_vertices = g2.size();
myset.erase (myset.find(v));
Graph_G = g2;
}
print_graph(g2);
min_cut = get_min_cut(g2);
return (min_cut);
}