#include <iostream> #include <algorithm> #include <queue> #define MAX 100 using namespace std; int dy[] = {1,-1,0,0}; int dx[] = {0,0,1,-1}; int map[MAX][MAX]; int visited[MAX][MAX]; int n,m; queue<pair<int, int> > q; bool isInside(int y, int x) { return (y >= 0 && x >= 0 && y < n && x < m); } int bfs(int startY, int startX) { int nowY = startY; int nowX = startX; q.push({nowY, nowX}); visited[nowY][nowX] = 1; while(!q.empty()) { nowY = q.front().first; nowX = q.front().second; q.pop(); if(!isInside(nowY,nowX)) continue; for(int i=0;i<4;i++) { int nextY = nowY + dy[i]; int nextX = nowX + dx[i]; if(isInside(nextY,nextX) && !visited[nextY][nextX] && map[nextY][nextX]) { visited[nextY][nextX] = visited[nowY][nowX] + 1; q.push({nextY, nextX}); } } } return visited[n-1][m-1]; } int main() { scanf("%d %d",&n,&m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) scanf("%1d",&map[i][j]); printf("%d",bfs(0,0)); }
BFS를 이용한 풀이입니다.
'Algorithm > Baekjoon & Algospot' 카테고리의 다른 글
[C++] BOJ 10822 - 더하기 (feat. how to convert string to int) (0) | 2018.04.02 |
---|---|
[C++] BOJ 2798 - 블랙잭 (0) | 2018.04.02 |
[C++]BOJ 1157 - 단어 공부 (0) | 2018.03.23 |
[C++] BOJ 2346 - 풍선 터뜨리기 (0) | 2018.03.22 |
[C++] BOJ 1182 - 부분집합의 합 (0) | 2018.03.20 |