#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <math.h>
#include <queue>
#include <vector>
using namespace std;
 
int row, col;
int map[110][110];
int visited[110][110];
 
queue<pair<intint>> q;
 
int dx[4= {-1100};
int dy[4= {00-11};
 
int safe(int x, int y)
{
    if(x >= 0 && y >= 0 && x < row && y < col)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
 
void BFS(int x, int y)
{
    q.push({x, y});
    visited[x][y] = 1;
    
    while(!q.empty())
    {
        x = q.front().first;
        y = q.front().second;
        q.pop();
        
        for(int i = 0; i < 4; i++)
        {
            int xpos = x+dx[i];
            int ypos = y+dy[i];
            
            if(safe(xpos, ypos) == 1 && map[xpos][ypos] == 1 && visited[xpos][ypos] == 0)
            {
                q.push({xpos, ypos});
                visited[xpos][ypos] = visited[x][y] + 1;
            }
        }    
    }
}
 
int main(void)
{
//    freopen("B2178_input.txt", "r", stdin);
    
    cin >> row >> col;
    
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < col; j++)
        {
            scanf("%1d"&map[i][j]);
        }
    }
    
    BFS(00);
    
    cout << visited[row-1][col-1];
    
    return 0;
}
cs

+ Recent posts