I am studying for my AI examination, and I am stuck in the Breath first search algorithm. According to the Breath first search algorithm, suppose a robot want to navigate from B to P on the following diagram.
I am suffering on finding the traversal using BFS and DFS.
Consider this matter may much appreciated.
I drew the diagram
I'm not quite sure what the actual question is, but here's some code I wrote to navigate a binary tree breadth-first:
# Print tree breadth-first
def breadthFirst(node):
stack = [[node]]
while len(stack[-1]) != 0:
newLevel = []
for node in stack[-1]:
if node.left != None:
newLevel.append(node.left)
if node.right != None:
newLevel.append(node.right)
if len(newLevel) == 0:
print('\n'.join('\n'.join(n.val for n in level) for level in stack))
stack.append(newLevel)
Related
This question already has answers here:
C How to "draw" a Binary Tree to the console [closed]
(10 answers)
Closed 3 years ago.
I know how to code a binary search tree, and to traverse it in inorder, preorder or postorder fashion.
But, I want to know how I can know where the actual node is:
For example let's say we have the values: 70 90 50 60 80 40
So the root would be 70, 90 to its right, 50 to its left, 60 to 50's right and so on.
So if I were to print this inorder, it would be 40 50 60 70 80 90, increasing order pretty much.
I do this by doing this in the recursive traverse function:
traverse(root->left);
printf("%d ", root->data);
traverse(root->right);
But this doesn't let me know (as far as I know) where the node currently is.
Is there a way to print the tree like this?:
70
50 (70 L) 90 (70 R) // We know which parent the node is from and we know if it's the left or the right of it.
40 (50 L) 60 (50 R) 80 (90 L)
and so on.. if the tree is bigger.
I don't really know how I'd do it. Would I need to link them to their parents? But how would I know the right-left thing if I do just that? Or do I need to print the child when the iterator is on the parent still. Thank you in advance.
Edit: I looked up printing the tree by traversing level by level but I don't think I get to know the parent and the side of the node.. I am trying to implement some codes to c code and I always get crashes.
Seems you want to print the tree level by level, i.e.
level 0: node0
level 1: node1 (node0 L) node2 (node0 R)
level 2: ...
So you need a way to track the current level and the target level (i.e. the one you want to print). Also you need a way to track when there is "no more levels" (i.e. no more to print).
That can be done in many ways. The pseudo code below should give you an idea of one way to do it. It's not the most efficient way but it's pretty simple.
Something like:
bool btPrintLevel(node* root, int targetlevel, int currentlevel)
{
if (targetlevel == currentlevel) return false; // no need to go further down in levels
bool result = false;
result |= btPrintLevel(root->left, targetlevel, currentlevel + 1);
// psedo code
if ((currentlevel + 1 == targetlevel)
{
if (childern_exists)
{
printChildern(...)
result = true;
}
}
result |= btPrintLevel(root->right, targetlevel, currentlevel + 1);
return result;
}
Called like:
int level = 0;
while(btPrintLevel(head, level)) ++level;
This How to print elements from Binary Tree by level in c may also help. It doesn't do exactly what you want but with minor modifications you can achieve your goal.
Recursive algorithms are fine for depth-first traversing of trees, but less suitable for broadth-first. The latter can be done pretty efficiently using a FIFO (pseudo code):
push(fifo, { root, 0 });
while(!isEmpty(fifo))
{
node* n = pop(fifo);
print(n);
if(n->left)
push(fifo, { n->left, 'L' });
if(n->right)
push(fifo, { n->right, 'R'});
}
I've foreseen an additional field designating being left or right child of parent. If you your nodes have a link to their parent, you can instead decide upon n->parent->left == n ? 'L' : 'R'.
Leaving implementing the FIFO up to you (you'll find quite a number of questions here on SO about)...
I need little help with DFS algorithm. I programmed application in C, that finds all possible paths between two vertexes in given graph.
The result (between vertexes 1 and 6) is in this format/order:
1-5-6,
1-6,
1-7-6
But my desire is to have them sorted by its length like this:
1-6,
1-5-6,
1-7-6
But I don't know how to sort them. For now whenever I find a new path I immediately print it to console output. I am sure that there is a way, how to do. Right now I cannot find it, so I am asking for help.
Thanks for answers.
EDIT
Example code, how I print paths, I reverse stack to have them in a correct order.
Stack *reverse = stack_new();
/* copy data of stack */
Node *temp = path->head;
while(temp != NULL)
{
stack_push(reverse, temp->data);
temp = temp->next;
}
if(reverse->size >= 1)
{
printf("%d", stack_pop(reverse));
}
while(stack_empty(reverse) == 0)
{
printf("-%d", stack_pop(reverse));
}
printf(";");
free(reverse);
I've implemented a Chess game in C, with the following structs:
move - which represents a move from (a,b) to (c,d) on a char board[8][8] (Chess board)
moves - which is a linked list of moves with head and tail.
Variables:
playing_color is 'W' or 'B'.
minimax_depth is a minimax depth that was set before.
Here is my code of the Minimax function with alpha-beta pruning and the getMoveScore function which should return the score of the move in Minimax Tree of a certain minimax_depth that was set before.
As well I'm using the getBestMoves function which I will also list here, it basicly find the best moves during the Minimax algorithm and saves them into a global variable so that I will be able to use them later.
I must add that all the functions that are listed within the three functions that I will add here are working properly and were tested, so the problem is either a logic problem of the alphabetaMax algorithm or the implementation of
getBestMoves/getMoveScore.
The problem mainly is that when I get my best moves at depth N (which are also not computed right somewhy) and then check their score on the same depth with getMoveScore function, I'm getting different scores that don't match the score of those actual best moves. I've spent hours on debugging this and couldn't see the error, I hope maybe anyone could give me a tip on finding the problem.
Here is the code:
/*
* Getting best possible moves for the playing color with the minimax algorithm
*/
moves* getBestMoves(char playing_color){
//Allocate memory for the best_moves which is a global variable to fill it in a minimax algorithm//
best_moves = calloc(1, sizeof(moves));
//Call an alpha-beta pruned minimax to compute the best moves//
alphabeta(playing_color, board, minimax_depth, INT_MIN, INT_MAX, 1);
return best_moves;
}
/*
* Getting the score of a given move for a current player
*/
int getMoveScore(char playing_color, move* curr_move){
//Allocate memory for best_moves although its not used so its just freed later//
best_moves = calloc(1, sizeof(moves));
int score;
char board_cpy[BOARD_SIZE][BOARD_SIZE];
//Copying a a current board and making a move on that board which score I want to compute//
boardCopy(board, board_cpy);
actualBoardUpdate(curr_move, board_cpy, playing_color);
//Calling the alphabeta Minimax now with the opposite color , a board after a given move and as a minimizing player, because basicly I made my move so its now the opponents turn and he is the minimizing player//
score = alphabeta(OppositeColor(playing_color), board_cpy, minimax_depth, INT_MIN, INT_MAX, 0);
freeMoves(best_moves->head);
free(best_moves);
return score;
}
/*
* Minimax function - finding the score of the best move possible from the input board
*/
int alphabeta(char playing_color, char curr_board[BOARD_SIZE][BOARD_SIZE], int depth,int alpha,int beta, int maximizing) {
if (depth == 0){
//If I'm at depth 0 I'm evaluating the current board with my scoring function//
return scoringFunc(curr_board, playing_color);
}
int score;
int max_score;
char board_cpy[BOARD_SIZE][BOARD_SIZE];
//I'm getting all the possible legal moves for the playing color//
moves * all_moves = getMoves(playing_color, curr_board);
move* curr_move = all_moves->head;
//If its terminating move I'm evaluating board as well, its separate from depth == 0 because only here I want to free memory//
if (curr_move == NULL){
free(all_moves);
return scoringFunc(curr_board,playing_color);
}
//If maximizing player is playing//
if (maximizing) {
score = INT_MIN;
max_score = score;
while (curr_move != NULL){
//Make the move and call alphabeta with the current board after the move for opposite color and !maximizing player//
boardCopy(curr_board, board_cpy);
actualBoardUpdate(curr_move, board_cpy, playing_color);
score = alphabeta(OppositeColor(playing_color), board_cpy, depth - 1,alpha,beta, !maximizing);
alpha = MAX(alpha, score);
if (beta <= alpha){
break;
}
//If I'm at the maximum depth I want to get current player best moves//
if (depth == minimax_depth){
move* best_move;
//If I found a move with a score that is bigger then the max score, I will free all previous moves and append him, and update the max_score//
if (score > max_score){
max_score = score;
freeMoves(best_moves->head);
free(best_moves);
best_moves = calloc(1, sizeof(moves));
best_move = copyMove(curr_move);
concatMoves(best_moves, best_move);
}
//If I have found a move with the same score and want to concatenate it to a list of best moves//
else if (score == max_score){
best_move = copyMove(curr_move);
concatMoves(best_moves, best_move);
}
}
//Move to the next move//
curr_move = curr_move->next;
}
freeMoves(all_moves->head);
free(all_moves);
return alpha;
}
else {
//The same as maximizing just for a minimizing player and I dont want to look for best moves here because I dont want to minimize my outcome//
score = INT_MAX;
while (curr_move != NULL){
boardCopy(curr_board, board_cpy);
actualBoardUpdate(curr_move, board_cpy, playing_color);
score = alphabeta(OppositeColor(playing_color), board_cpy, depth - 1,alpha,beta, !maximizing);
beta = MIN(beta, score);
if (beta <= alpha){
break;
}
curr_move = curr_move->next;
}
freeMoves(all_moves->head);
free(all_moves);
return beta;
}
}
As Eugene has pointed out-I'm adding an example here:
http://imageshack.com/a/img910/4643/fmQvlm.png
I'm currently the white player, i got only king-k and queen-q, the opposite color has king-K and rook-R. Obviously my best move here is to eat a rook or cause a check at least. Moves of the pieces are tested and they work fine. Although when i call get_best_moves function at depth 3, I'm getting lots of unnecessary moves and negative scores for them at that depth. Maybe now it's a little more clear. Thanks!
Without debugging your whole code, at least ONE of the problems is the fact that your scoreverification might work with a minimax algorithm, but not with a Alpha-Beta. Following problem:
The getMoveScore() function has to start with an open AB Window.
The getBestMoves() however call getMoveScore() with an already closed AB Window.
So in the case of getBestMoves, there can be branches pruned that are not being pruned in getMoveScore(), therefore the score not being exact, and thats the reason (or at least ONE of them) why these valued can differ.
I want to know if its possible to modify an existing chess engine in C that works without multi-threading to be able to support multi-threading. I have no experience in this subject and would appreciate some guidance.
EDIT: To be more specific, is there anything I can add to my implementation of negamax to make it multi-thread compatible? :
static double alphaBetaMax(double alpha, double beta, int depthleft, game_t game, bool player)
{
move_t *cur;
move_t *tmp;
double score = 0;
bool did_move = false;
cur = getAllMoves(game, player);
if(cur == NULL) /*/ check mate*/
return -9999999*(player*2-1);
tmp = firstMove;
firstMove = 0;
while (cur != NULL)
{
game_t copy;
if(depthleft<=0 && !isCapture(game, cur)) { /* Quiescence search */
cur = cur->next;
continue;
}
did_move = true;
copyGame(game, ©);
makeMove(©, *cur);
firstMove = NULL;
score = -alphaBetaMax(-beta, -alpha, depthleft - 1, copy, !player);
if(board_count > MAX_BOARDS)
break;
freeGame(copy);
if(score > alpha)
alpha = score;
if (beta <= alpha)
break;
cur = cur->next;
}
firstMove=tmp;
freeMoves();
if(!did_move)
alpha = evaluate(game)*(player*2-1);
return alpha;
}
A fast chess engine relies on two things: Caching the evaluation of positions, and the alpha/beta strategy. Caching positions and making it thread safe and fast is hard. The alpha/beta strategy relies on the seemingly best move being completely evaluated before you start evaluating other moves. This also makes it tough to use multiple threads.
Beginner composer to Mozart: "Can you tell me how to compose a symphony"? Mozart to beginner: "Maybe at your young age you should try something easier first. " Beginner to Mozart: "But you wrote symphonies when you were much younger than I am now. " Mozart to beginner: "True, but I didn't have to ask anyone".
The Alpha-Beta pruning is inherently single-threaded in nature. There's been successful approaches using variations of Dynamic Tree Splitting which basically means searching various branches at the same time. However the likelihood (in a well tuned engine) that next branch will be searched (or beta-cut) does not usually outweigh the other parallelism bottlenecks like memory waits.
I would suggest, first modify your search to a "re-search" algorithm like NegaScout or PVS which with small code changes will give good improvements over your current pure Alpha-Beta, then secondly fine-tune your move ordering to yield efficient beta-cut.
Thereafter you could try to split the tree based on beta-cut chances. Typically there would be higher chance of cutoff when a move is found in the transposition-table or a killer move and lesser chance when starting to search bad captures and quiet moves.
Take a look at CPW for some thoughts on it and the YBWC algorithm.
Young Brothers Wait Concept
I'm currently writing a c++ chess engine and I have made a quite simple but not optimal solution:
First I'm generating all moves in the form of a list of structs
I start n threads which repeatedly grab "jobs" from the list
do their search and write back the result into the struct. When the
list is empty, a thread kills itself.
In the general search function I join the threads and loop through the results afterwards.
Is this approach most efficient?
As currently the focus on searching the most relevant moves first but you'll eventually look at all moves and also hardly get a cutoff at depth one but works fine
Simple to implement and in any case better than a "one-cpu" search. Even if one move takes way more time - it's running on one cpu, like back then :D
Maybe start out with that
I have completed a red black tree in c and i find it hard to print it in level-order. I have a print-inorder but i cant imagine how am i supposed to display it as a tree in the console print. Is it feasible? Can we implement BFS or DFS here? i've found an algorithm in wiki but i cant apply it.
If anyone has code for it in C could you post it here so i can study it?
from wiki:
levelorder(root)
q = empty queue
q.enqueue(root)
while not q.empty do
node := q.dequeue()
visit(node)
if node.left ≠ null
q.enqueue(node.left)
if node.right ≠ null
q.enqueue(node.right)
You can do a BFS, but it might be easier to do an iterative deepening search, since that will save you the trouble of implementing a FIFO queue in C. Pseudocode:
algorithm iterative-deepening(root)
D = max-depth(root)
for d=0 to D
depth-limited-search(root, d)
/* variant of DFS */
algorithm depth-limited-search(node, d)
if node != NULL
if d == 0
print node.contents
else
depth-limited-search(node.left, d - 1)
depth-limited-search(node.right, d - 1)