Guest User

Untitled

a guest
Nov 17th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <queue>
  4. #include <vector>
  5. using namespace std;
  6. int n, m, ans;
  7. int map[101][101];
  8. int dr[] = { -1,0,1,0 };
  9. int dc[] = { 0,-1,0,1 };
  10. queue<pair<int,int>> q;
  11. void bfs() {
  12. int r, c, nr, nc;
  13. q.push({ 0, 0 });
  14. map[0][0] = 2;
  15. while (!q.empty()) {
  16. r = q.front().first;
  17. c = q.front().second;
  18. q.pop();
  19. for (int i = 0; i < 4; i++) {
  20. nr = r + dr[i];
  21. nc = c + dc[i];
  22. if (0 <= nr && nr < n && 0 <= nc && nc < m) {
  23. if (map[nr][nc] == 1) {
  24. map[nr][nc] = map[r][c]+1;
  25. q.push({ nr,nc });
  26. if (nr == n - 1 && nc == m - 1) {
  27. ans = map[nr][nc];
  28. break;
  29. }
  30. }
  31. }
  32. }
  33. }
  34. }
  35. int main() {
  36. scanf("%d %d", &n, &m);
  37. for (int i = 0; i < n; i++) {
  38. for (int j = 0; j < m; j++) {
  39. scanf(" %1d", &map[i][j]);
  40. }
  41. }
  42. bfs();
  43.  
  44. for (int i = 0; i < n; i++) {
  45. for (int j = 0; j < m; j++) {
  46. printf("%d ", map[i][j]);
  47. }
  48. printf("\n");
  49. }
  50. printf("%d\n", ans-1);
  51. return 0;
  52. }
Add Comment
Please, Sign In to add comment