본문 바로가기
코테

백준 2178번 - 미로 탐색

by arirang_ 2023. 11. 8.
#include <bits/stdc++.h>
using namespace std;

int n, m, y, x, ny, nx, visited[103][103];
char adj[103][103];

int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};

//최단경로 문제-> bfs 이용 

int main(){
	
	cin >> n >> m;
	
	
	for(int i=1; i<=n; i++){
		for(int j=1; j<=m; j++){
			cin >> adj[i][j];
		}
	}
	
	queue<pair<int, int>> q;
	visited[1][1] = 1;
	q.push({1,1});
	
	while(q.size()){
		tie(y, x) = q.front(); q.pop();
		
		for(int i=0; i<4; i++){
			ny = y + dy[i];
			nx = x + dx[i];
			
			if(ny <= 0 || nx <=0 || ny>n || nx>m || adj[ny][nx]=='0')continue;
			if(visited[ny][nx]) continue;
			visited[ny][nx] = visited[y][x] +1;
			q.push({ny, nx});
		}
	}
	
	cout << visited[n][m] << "\n";
	
	
	return 0;
}

 

* 좌표 2개 담을 수 있는 pair로 queue 정의

* 오버플로우 먼저 체크하고 adj[ny][nx]=='0'  
  (건널 수 없는 강(배열의 범위)인지 먼저 체크하기)

 

 

[참고]

* 따닥따닥 붙어있는 것 입력으로 받기

- scanf 사용

scanf("%1d", &a[i][j])

 

'코테' 카테고리의 다른 글

[BOJ] 부분수열의 합  (1) 2024.08.06
[BOJ] 두 스티커  (0) 2024.08.05
[queue]백준 10845번 - 큐  (0) 2023.10.01
[stack]백준 9012번 - 괄호  (1) 2023.10.01
[stack]백준 10828번 - 스택  (0) 2023.10.01