fork download
  1. #include <iostream>
  2. #include <queue>
  3. #include <tuple>
  4. #include <climits>
  5.  
  6. #define MAXN 100
  7. using namespace std;
  8.  
  9. int N, M; //상자의 가로, 세로 칸 수
  10. int mapx[MAXN+10][MAXN+10]; //미로 정보
  11. int visited[MAXN+10][MAXN+10]; // 방문 정보 및 이동 횟수 저장
  12. queue<tuple<int,int,int>> q;
  13.  
  14. void InputData(){
  15. cin >> N >> M;
  16. for (int i=0; i<N; i++){
  17. for (int j=0; j<M; j++){
  18. scanf("%1d", &mapx[i][j]);
  19. printf("%d ", mapx[i][j]);
  20. }
  21. printf("\n");
  22. }
  23. }
  24.  
  25. int solve(int x, int y)
  26. {
  27. int tmpx = 0, tmpy = 0, tmpt = 0;
  28. int ret = INT_MAX;
  29. q.push(make_tuple(x,y,1));
  30. visited[x][y] = 1;
  31. int ax[] = {-1,1,0,0};
  32. int ay[] = {0,0,-1,1};
  33.  
  34. while(!q.empty())
  35. {
  36. tmpx = get<0>(q.front());
  37. tmpy = get<1>(q.front());
  38. tmpt = get<2>(q.front());
  39. q.pop();
  40.  
  41. // printf("(x,y,t) -> %d, %d, %d\n", tmpx, tmpx, tmpt);
  42.  
  43. for(int i = 0; i < 4; i++)
  44. {
  45. int calcx = tmpx + ax[i];
  46. int calcy = tmpy + ay[i];
  47.  
  48. if( (0 <= calcx && calcx < N) && (0 <= calcy && calcy < M) // 범위를 벗어 나지 않고
  49. && mapx[calcx][calcy] == 1 // 가로막힌 공간이 아니고
  50. && visited[calcx][calcy] == 0 ) // 방문하지 않았을 때
  51. {
  52. q.push(make_tuple(calcx,calcy,tmpt+1));
  53. visited[calcx][calcy] = tmpt+1;
  54. }
  55. }
  56. }
  57.  
  58. return visited[N-1][M-1];
  59. }
  60.  
  61. int main()
  62. {
  63. ios_base::sync_with_stdio(false);
  64. cin.tie(NULL);
  65. cout.tie(NULL);
  66. int ans = -1;
  67.  
  68. InputData();//입력
  69.  
  70. //여기서부터 작성
  71. ans = solve(0,0);
  72.  
  73. printf("%d\n", ans);
  74. return 0;
  75. }
Success #stdin #stdout 0s 5296KB
stdin
4 6
101111
101010
101011
111011
stdout
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0