Cub3D
Loading...
Searching...
No Matches
flood_fill.c
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* flood_fill.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: kamitsui <kamitsui@student.42tokyo.jp> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/12/01 02:42:15 by kamitsui #+# #+# */
9/* Updated: 2024/12/17 03:20:15 by kamitsui ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "cub3d.h"
14
15int init_stack(t_stack *stack, int initial_capacity)
16{
17 stack->data = (t_point *)malloc(initial_capacity * sizeof(t_point));
18 if (stack->data == NULL)
19 {
20 perror("Failed to allocate stack\n");
21 return (EXIT_FAILURE);
22 }
23 stack->top = 0;
24 stack->capacity = initial_capacity;
25 return (EXIT_SUCCESS);
26}
27
33static int push_neighbors_onto_stack(int x, int y, t_stack *stack)
34{
35 static int dx[4] = {0, 0, -1, 1};
36 static int dy[4] = {-1, 1, 0, 0};
37 int new_x;
38 int new_y;
39 int i;
40
41 i = 0;
42 while (i < 4)
43 {
44 new_x = x + dx[i];
45 new_y = y + dy[i];
46 if (push(stack, (t_point){new_x, new_y}) != EXIT_SUCCESS)
47 return (EXIT_FAILURE);
48 i++;
49 }
50 return (EXIT_SUCCESS);
51}
52
62int check_grid_is_not_visited(t_point current, t_map *map,
63 t_bool *is_surrounded, bool **visited)
64{
65 if (current.x < 0 || current.x >= map->width
66 || current.y < 0 || current.y >= map->height)
67 {
68 *is_surrounded = ENUM_FALSE;
69 return (CONTINUE);
70 }
71 if (visited[current.y][current.x] == true
72 || map->data[current.y][current.x] == '1')
73 {
74 if (map->data[current.y][current.x] != '0'
75 && map->data[current.y][current.x] != '1')
76 *is_surrounded = ENUM_FALSE;
77 return (CONTINUE);
78 }
79 return (EXIT_SUCCESS);
80}
81
82int initialize_for_flood_fill(t_stack *stack, int start_x, int start_y)
83{
84 if (init_stack(stack, DFLT_STACK_SIZE) != EXIT_SUCCESS)
85 return (EXIT_FAILURE);
86 if (push(stack, (t_point){start_x, start_y}) != EXIT_SUCCESS)
87 {
88 free(stack->data);
89 return (EXIT_FAILURE);
90 }
91 return (EXIT_SUCCESS);
92}
93
99t_bool flood_fill(t_map *map, int start_x, int start_y, bool **visited)
100{
101 t_stack stack;
102 t_bool is_surrounded;
103 t_point current;
104
105 if (initialize_for_flood_fill(&stack, start_x, start_y) != EXIT_SUCCESS)
106 return (ENUM_ERROR);
107 is_surrounded = ENUM_TRUE;
108 while (is_empty(&stack) == false)
109 {
110 current = pop(&stack);
111 if (check_grid_is_not_visited(current, map, &is_surrounded, visited)
112 == CONTINUE)
113 continue ;
114 visited[current.y][current.x] = true;
115 if (push_neighbors_onto_stack(current.x, current.y, &stack)
116 != EXIT_SUCCESS)
117 {
118 is_surrounded = ENUM_ERROR;
119 break ;
120 }
121 }
122 free(stack.data);
123 return (is_surrounded);
124}
game map
Definition type_cub3d.h:237