9oormthon 탐색 1일차: 발전기

PEA은하·2023년 8월 30일
post-thumbnail

Submitted Code

Python

N = int(input())
maps = []

for i in range(N):
	row = list(map(int, input().split()))
	maps.append(row)
	
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
stack = []
power_plant = 0
for i in range(N):
	for j in range(N):
		if not maps[i][j]:
			continue
		stack.append((i, j))
		maps[i][j] = 0
		power_plant += 1
		while stack:
			y, x = stack.pop()				
			for dy, dx in dirs:
				ny, nx = y + dy, x + dx
				if ny in (-1, N) or nx in (-1, N):
					continue
				
				if maps[ny][nx]:
					stack.append((ny, nx))
					maps[ny][nx] = 0
					
print(power_plant)

C++

#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int main() {
	int N;
	cin >> N;
	
	int maps[1000][1000] = {};
	for (int i = 0; i < N; i++){
		for (int j = 0; j < N; j++){
			int tmp;
			cin >> tmp;
			maps[i][j] = tmp;
		}
	}
	
	queue<pair<int, int>> queue;
	int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
	int cnt_plant = 0;
	for (int i = 0; i < N; i++){
		for (int j = 0; j < N; j++){
			if (maps[i][j]) {
				queue.push(make_pair(i, j));
				maps[i][j] = 0;
				cnt_plant++;
			}
			
			while (queue.size()) {
				pair<int, int> pos(queue.front().first, queue.front().second);
				queue.pop();
				for (int k = 0; k < 4; k++){
					pair<int, int> npos(pos.first + dirs[k][0], pos.second + dirs[k][1]);
					if (npos.first < 0 || npos.first >= N || npos.second < 0 || npos.second >= N) 
						continue;
					
					int Mrc = maps[npos.first][npos.second];
					if (Mrc == 0) continue;
					else {
						queue.push(npos);
						maps[npos.first][npos.second] = 0;
					}
				}
			}			
		}
	}
	
	cout << cnt_plant;
	return 0;
}

0개의 댓글