-
Notifications
You must be signed in to change notification settings - Fork 0
/
785.cpp
120 lines (98 loc) · 2.68 KB
/
785.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* Problem : 785 - Grid Colouring.
* Verdict : Accepted.
* Writer : Mehadi Hasan Menon.
* Date : 24.12.16.
**/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <vector>
using namespace std;
char maze[50][100];
char contours_char;
int dr[] = {-1, 0, 1, 0};
int dc[] = {0, 1, 0, -1};
void dfs(int r, int c, char marking_char)
{
if(maze[r][c] == contours_char || maze[r][c] == marking_char) {
return;
}
if(maze[r][c] == ' ')
{
maze[r][c] = marking_char;
for(int i = 0; i < 4; i++)
{
int new_row = r + dr[i];
int new_col = c + dc[i];
// traverse all adjacent
dfs(new_row, new_col, marking_char);
}
}
}
int main()
{
freopen("input.txt", "r+", stdin);
char line[100];
bool found_contours_char = false;
int r = 0;
vector < pair<int, int> > vip_index;
vector <char> vc_marking_char;
while(gets(line))
{
// find contours char
if(found_contours_char == false)
{
for(int c = 0; line[c]; c++)
{
if(isprint(line[c]) && line[c] != ' ')
{
contours_char = line[c];
found_contours_char = true;
break;
}
}
}
// find all marking_char's position
for(int c = 0; line[c]; c++)
{
if(line[c] != contours_char && line[c] != ' ' && line[c] != '_')
{
int marking_char_row = r;
int marking_char_col = c;
// track the location of marking char in maze & and the char itself
vip_index.push_back(make_pair(marking_char_row, marking_char_col));
vc_marking_char.push_back(line[c]);
}
}
strcpy(maze[r], line);
r += 1;
if(line[0] == '_')
{
int sz = vip_index.size();
int row, col;
char marking_char;
for(int contours = 0; contours < sz; contours++)
{
row = vip_index[contours].first;
col = vip_index[contours].second;
marking_char = vc_marking_char[contours];
// for 1st time dfs call
maze[row][col] = ' ';
// fill all
dfs(row, col, marking_char);
vip_index.clear();
vc_marking_char.clear();
}
// print result
for(int i = 0; i < r; i++)
{
puts(maze[i]);
}
r = 0;
found_contours_char = false;
}
}
return 0;
}