BOJ::2178 미로 탐색
https://www.acmicpc.net/problem/2178
bfs를 이용해 미로의 최단경로를 구하는 문제.
<JAVA>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { static int n,m,x,y,ax,ay; static int map[][]=new int[101][101]; static int dx[]={1,-1,0,0}; static int dy[]={0,0,1,-1}; public static void main(String args[]) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n=Integer.parseInt(st.nextToken()); m=Integer.parseInt(st.nextToken()); for(int i = 1 ; i<= n; i++){ String s = br.readLine(); for(int j = 1 ; j <= m ; j++){ map[i][j]=s.charAt(j-1)-'0'; } } bfs(1,1); System.out.println(map[n][m]); } public static void bfs(int a,int b){ Queue<Node> q = new LinkedList(); q.add(new Node(a,b)); while(!q.isEmpty()){ x = q.peek().x; y = q.poll().y; for(int i = 0 ; i < 4 ; i++){ ax = x+dx[i]; ay = y+dy[i]; if(ax>0&&ay>0&&ax<=n&&ay<=m){ if(map[ax][ay]!=0){ if(map[ax][ay]==1 || map[ax][ay]>map[x][y]+1){ map[ax][ay]=map[x][y]+1; q.add(new Node(ax,ay)); } } } } } } } class Node{ int x; int y; Node(int _x, int _y){ x=_x; y=_y; } } | cs |
<C++>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <iostream> #include <string> #include <queue> using namespace std; int n, m, x, y, ax, ay; int map[101][101]; int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1 }; class Node { public: int x; int y; Node(int _x, int _y) { x = _x; y = _y; } }; void bfs(int a, int b) { queue<Node> q; q.push(Node(a, b)); while (!q.empty()) { x = q.front().x; y = q.front().y; q.pop(); for (int i = 0; i < 4; i++) { ax = x + dx[i]; ay = y + dy[i]; if (ax > 0 && ay > 0 && ax <= n && ay <= m) { if (map[ax][ay] != 0) { if (map[ax][ay] == 1 || map[ax][ay] > map[x][y] + 1) { map[ax][ay] = map[x][y] + 1; q.push(Node(ax, ay)); } } } } } } int main() { cin >> n >> m; for (int i = 1; i <= n; i++) { string s; cin >> s; for (int j = 1; j <= m; j++) { map[i][j] = s.at(j - 1) - '0'; } } bfs(1, 1); cout << map[n][m] << endl; } | cs |
'BOJ::문제풀이' 카테고리의 다른 글
2206 벽 부수고 이동하기 (2) | 2018.01.01 |
---|---|
2193 이친수 (0) | 2018.01.01 |
2156 포도주 시식 (0) | 2018.01.01 |
2096 내려가기 (0) | 2018.01.01 |
1987 알파벳 (0) | 2018.01.01 |