본문 바로가기

알고리즘

[DFS] 백준 전투 - 1303, 백준 그림 - 1926 (SOS)

백준 전투(1303) - 테스트 케이스 맞는데 뭐가 틀린지 도저히 모르겠다. 결과 : 틀렸습니다

백준 그림(1926) - dev C++ 에서 테스트 케이스는 맞음. 결과 : 런타임에러

 

해결책 댓글 달아주시면 음료 기프티콘 보내드릴게요!!, 카톡 아이디 남겨주세여

 

전투.cpp

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cmath> 
#include<stdlib.h>
using namespace std;

int N,M; // 입력값 
int eachPower, eachPower2; // 병사수 
char map[100][100], cpy[100][100]; // 전쟁터 
int dx[] = {0,0,-1,1}; // 상하좌우 움직이는 템플릿 
int dy[] = {-1,1,0,0}; // 상하좌우 움직이는 템플릿 
vector<int> wPower, bPower; // 위력을 담는 vector


void dfs(int x, int y){

eachPower++; // 병사수 증가 
map[x][y] = 'F'; // 'B', 'W'가 아닌 값으로 임의로 치환 

for(int i=0; i<4; i++){ // 템플릿 (탐색) 

int nx = x + dx[i];
int ny = y + dy[i];

if(nx>=N || ny>=M || nx<0 || ny<0 || map[nx][ny] == 'F' || map[nx][ny] == 'B') continue; // 'F' 인 경우 무시

if(map[nx][ny] == 'W'){ 
 dfs(nx,ny); // 깊이우선탐색 
}
}
}

void dfs2(int x, int y){

eachPower2++; // 병사수 증가 
cpy[x][y] = 'F'; // 'B', 'W'가 아닌 값으로 임의로 치환 

for(int i=0; i<4; i++){ // 템플릿 (탐색) 

int nx = x + dx[i];
int ny = y + dy[i];

if(nx>=N || ny>=M || nx<0 || ny<0 || cpy[nx][ny] == 'F' || cpy[nx][ny] == 'W') continue; // 'F' 인 경우 무시

if(cpy[nx][ny] == 'B'){ 
 dfs2(nx,ny); // 깊이우선탐색 
}
}
}


int main(){

cin >> N >> M;

for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
cin >> map[i][j];
}
}


for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
cpy[i][j] = map[i][j];
}
}

for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
if(map[i][j] == 'W'){
eachPower = 0;
dfs(i,j);
wPower.push_back(eachPower);
}
}
}

for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
if(cpy[i][j] == 'B'){
eachPower2 = 0;
dfs2(i,j);
bPower.push_back(eachPower2);
}
}
}

int wSize = wPower.size(); // 하얀팀 지수 값
int bSize = bPower.size(); // 파란팀 지수 값


int wRst = 0, bRst = 0;

for(int i=0; i<wSize; i++){
wRst += pow(wPower[i],2);
}

for(int i=0; i<bSize; i++){
bRst += pow(bPower[i],2);
}

printf("%d %d", wRst, bRst);

return 0;
}

 

 

 

그림.cpp

// 백준 1926 그림 -- 유사한 문제  

#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;


int n,m;
int paper[500][500] = {0,};
vector<int> srt;
int area;
int dx[] = {0,0,-1,1};
int dy[] = {-1,1,0,0};


void dfs(int x, int y){

paper[x][y] = 0;
area++;

for(int i=0; i<4; i++){
int nx = x + dx[i];
int ny = y + dy[i];

if(nx < 0 || ny < 0 || nx >= n || ny >= m || paper[nx][ny] == 0) continue;

dfs(nx,ny);
}

}



int main(){


cin >> n >> m;

for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
scanf("%d",&paper[i][j]);
}
}


for(int i=0; i<n; i++){
for(int j=0; j<m; j++){

if(paper[i][j] == 1){
area = 0;
dfs(i,j);
srt.push_back(area);
}
}
}

sort(srt.begin(),srt.end());


cout << srt.size() << endl;
cout << srt[srt.size()-1] << endl;





return 0;

}