We need to write a program to count number of islands (connected components of 1's) in each 12x12 grid. Input: multiple datasets, each dataset is 12 lines of 12 characters each (1 or 0). Datasets separated by a blank line. At most 20 datasets.
We need to output number of islands per dataset.
Approach: read lines until EOF. For each dataset, collect 12 lines (skip empty lines?). The blank line separates datasets, but could be leading/trailing? Usually, we can read all lines, then parse.
Simpler: read entire input as list of lines. Then iterate: if line.strip() is empty, treat as separator; else accumulate lines. Since each dataset exactly 12 lines of 12 chars, we can just read 12 lines ignoring blank lines. But careful: there might be blank lines between datasets. So we can read lines, skip empty lines, and for each group of 12 non-empty lines we process as dataset. However, if there are blank lines inside a dataset? No, each dataset is exactly 12 rows without blanks. So we can read lines, filter out empty ones, then chunk into groups of 12.
But caution: the input could have trailing newline after last dataset, but that's fine. Also there may be multiple blank lines? The problem says datasets separated by a single blank line, but we can be robust.
So algorithm: read all lines from sys.stdin. Remove trailing newline. For each line, if line.strip() != "" (i.e., not empty after stripping spaces? The problem uses only 0/1, no spaces; but blank lines might have spaces? Unlikely) then keep. Then process groups of 12 lines.
For each group of 12 strings of length 12 (maybe they could have extra whitespace? Usually not, but we can strip whitespace). Convert to 12x12 grid of characters/int.
Then do BFS/DFS to count connected components of '1's using 4-directional adjacency.
Implement BFS using queue, or simple recursion? 12x12=144 cells, trivial.
We'll mark visited.
Pseudo:
def count_islands(grid):
m,n = 12,12
visited = [[False]*n for _ in range(m)]
count = 0
for i in range(m):
for j in range(n):
if grid[i][j]=='1' and not visited[i][j]:
count += 1
# BFS/DFS
stack = [(i,j)]
visited[i][j] = True
while stack:
x,y = stack.pop()
for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx, ny = x+dx, y+dy
if 0<=nx<m and 0<=ny<n and grid[nx][ny]=='1' and not visited[nx][ny]:
visited[nx][ny]=True
stack.append((nx,ny))
return count
Now reading: The example input shows three datasets separated by blank line. So our approach should work.
Edge cases: The number of datasets not exceed 20. No blank lines at start? Possibly. But we'll handle.
Implementation details: Use sys.stdin.read().splitlines() to get lines. Then filter out lines that are empty after stripping? But careful: if we strip whitespace, a line with spaces could become empty; treat as blank. So we can do lines = [line.strip() for line in sys.stdin.readlines()] then filter out if line == ""; then group by 12.
But note: Could there be lines that have spaces? The input format says 12 rows of 12 number columns; no spaces. So fine.
Thus final code:
import sys
def solve():
data = sys.stdin.read().splitlines()
# Remove possible trailing newline? Already handled.
datasets = []
current = []
for line in data:
line = line.strip()
if line == "":
if current:
datasets.append(current)
current = []
else:
current.append(line)
if current:
datasets.append(current)
# But note: some datasets might not be separated by blank line but just consecutive? Problem says separated by blank line. So above works.
# However, what if there are extra blank lines at start? Then current would be empty, we ignore.
# But also we need to ensure each dataset has exactly 12 lines. However, we can trust the input.
for dataset in datasets:
if len(dataset) != 12:
# maybe due to extra blank lines grouping? But we grouped by blank lines, but if there is blank line within dataset it's invalid. So assume correct.
continue
grid = [list(row) for row in dataset] # each row is string of 0/1
print(count_islands(grid))
def count_islands(grid):
m,n = 12,12
visited = [[False]*n for _ in range(m)]
count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1' and not visited[i][j]:
count += 1
# BFS
stack = [(i,j)]
visited[i][j] = True
while stack:
x,y = stack.pop()
for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx, ny = x+dx, y+dy
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == '1' and not visited[nx][ny]:
visited[nx][ny] = True
stack.append((nx,ny))
return count
if name == "main":
solve()
But wait: The sample input includes lines like "111100001111" exactly 12 characters. So fine.
Testing with sample:
Dataset1 grid: output should be 5.
Check: we can test manually? Probably correct.
One nuance: The blank line might be present but our grouping will treat it as separator; if there is blank line at the end, current may have already been appended. Should be fine.
Alternatively, we could use a simpler approach: read lines until EOF; for each non-empty line, add to current; after reading 12 lines, process; then continue. But we need to handle blank lines that separate. So we can read all lines and ignore empty lines, then partition into groups of 12. That's simpler and robust: lines = [line.strip() for line in sys.stdin.read().splitlines() if line.strip()!='']; then chunk into groups of 12.
But what if there is a blank line inside a dataset? Not according to problem. So that's fine.
Thus we can do:
lines = [line.strip() for line in sys.stdin.read().splitlines()]
valid_lines = [line for line in lines if line != '']
num_datasets = len(valid_lines) // 12
for k in range(num_datasets):
grid = [list(valid_lines[k*12 + i]) for i in range(12)]
print(count_islands(grid))
But careful: if there are extra blank lines at the end, valid_lines length still multiple of 12? Should be because each dataset exactly 12 lines. So this works.
Let's pick that approach.
Implementation:
import sys
def count_islands(grid):
m,n = 12,12
visited = [[False]*n for _ in range(m)]
count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1' and not visited[i][j]:
count += 1
stack = [(i,j)]
visited[i][j] = True
while stack:
x,y = stack.pop()
for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx,ny = x+dx, y+dy
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == '1' and not visited[nx][ny]:
visited[nx][ny] = True
stack.append((nx,ny))
return count
def solve():
data = sys.stdin.read().splitlines()
# filter out empty lines
non_empty = [line.strip() for line in data if line.strip() != '']
# assume each dataset has exactly 12 lines
for i in range(0, len(non_empty), 12):
grid = [list(non_empty[i+j]) for j in range(12)]
print(count_islands(grid))
if name == 'main':
solve()
Test with sample.
Now confirm sample output:
First dataset: 5
Second: 13
Third: 4
Our code should produce that.
But also we need to check the sample input format: they provided three datasets with blank lines in between. Our filter method will ignore blank lines, leaving 36 lines. So three groups. Good.
Thus final answer.
But maybe there could be trailing spaces? We strip lines, which removes leading/trailing spaces. Should be okay. However, stripping might remove trailing characters if there is space? But unlikely. Could we accidentally strip out zeros? No, strip removes whitespace, zeros are not whitespace. So fine.
We might also consider using recursion, but iterative is fine.
One more nuance: The problem statement included a hint with some ascii art; ignore.
Thus final answer: Provide Python code with BFS.
We'll output the code. ```python
import sys
def count_islands(grid):
"""Return the number of connected components of '1' in a 12x12 grid."""
m = n = 12
visited = [[False] * n for _ in range(m)]
count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1' and not visited[i][j]:
count += 1
# DFS (stack)
stack = [(i, j)]
visited[i][j] = True
while stack:
x, y = stack.pop()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n
and grid[nx][ny] == '1' and not visited[nx][ny]:
visited[nx][ny] = True
stack.append((nx, ny))
return count
def solve():
# Read all lines, keep only non‑empty ones (datasets are separated by blank lines)
lines = sys.stdin.read().splitlines()
non_empty = [ln.strip() for ln in lines if ln.strip() != '']
# Process each group of 12 lines as one dataset
for start in range(0, len(non_empty), 12):
dataset = non_empty[start:start + 12]
# Convert each string into a list of characters (rows of the grid)
grid = [list(row) for row in dataset]
print(count_islands(grid))
if name == "main":
solve()