norminetted backtrack.c and get_cur_pos.c

This commit is contained in:
Steffen Matthes 2023-03-26 22:51:09 +02:00
parent d340b998cb
commit 226e625e16
2 changed files with 55 additions and 41 deletions

View File

@ -1,27 +1,40 @@
#include <stdio.h> /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* backtrack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: smatthes <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/26 22:44:15 by smatthes #+# #+# */
/* Updated: 2023/03/26 22:47:19 by smatthes ### ########.fr */
/* */
/* ************************************************************************** */
int is_valid_state(int **board, int *borders, int *pos, int n); int is_valid_state(int **board, int *borders, int *pos, int n);
void get_cur_pos(int **board, int *pos, int n); void get_cur_pos(int **board, int *pos, int n);
void print_board(int **board, int n); void print_board(int **board, int n);
int backtrack(int **board, int *borders, int rec_depth, int n) int backtrack(int **board, int *borders, int rec_depth, int n)
{ {
int pos[2]; int pos[2];
get_cur_pos(board, pos, n); int y;
int y = pos[0]; int x;
int x = pos[1]; int counter;
if (rec_depth == n * n)
{ get_cur_pos(board, pos, n);
return (1); y = pos[0];
} x = pos[1];
int counter = 0; if (rec_depth == n * n)
while (++counter < n + 1) {
{ return (1);
board[y][x] = counter; }
if (is_valid_state(board, borders, pos, n) == 1) while (++counter < n + 1)
if (backtrack(board, borders, rec_depth + 1, n) == 1) {
return (1); board[y][x] = counter;
if (is_valid_state(board, borders, pos, n) == 1)
if (backtrack(board, borders, rec_depth + 1, n) == 1)
return (1);
board[y][x] = 0; board[y][x] = 0;
} }
return (0); return (0);
} }

View File

@ -6,28 +6,29 @@
/* By: smatthes <marvin@42.fr> +#+ +:+ +#+ */ /* By: smatthes <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/26 21:56:39 by smatthes #+# #+# */ /* Created: 2023/03/26 21:56:39 by smatthes #+# #+# */
/* Updated: 2023/03/26 21:56:44 by smatthes ### ########.fr */ /* Updated: 2023/03/26 22:49:45 by smatthes ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#include <stdio.h>
void get_cur_pos(int **board, int *pos, int n) void get_cur_pos(int **board, int *pos, int n)
{ {
int i = -1; int i;
int j = -1; int j;
while (++i < n)
{ i = -1;
while (++j < n) j = -1;
{ while (++i < n)
if (board[i][j] == 0) {
{ while (++j < n)
pos[0] = i; {
pos[1] = j; if (board[i][j] == 0)
return; {
} pos[0] = i;
} pos[1] = j;
j = -1; return ;
} }
return; }
j = -1;
}
return ;
} }