简体   繁体   English

c ++算法为什么无限循环

[英]c++ Algorithm Why does an infinite loop go around

I was trying to solve a problem on the algorithm site and asked a question because I couldn't catch the error.我试图解决算法站点上的问题并提出了一个问题,因为我无法捕捉到错误。

I can't understand why the infinite loop goes.我不明白为什么无限循环会发生。 My algorithmic logic is correct.我的算法逻辑是正确的。 Because if you remove the while in the main statement and print it for each case, the infinite loop does not run.因为如果删除主语句中的 while 并为每种情况打印它,则无限循环不会运行。

The problem site is below.问题站点如下。 can you help me?你能帮助我吗?

https://www.acmicpc.net/problem/11370 https://www.acmicpc.net/problem/11370

#include <iostream>
#include <vector>
#include <queue>
#include <tuple>
#include <string>
using namespace std;
int w, h;
int dx[]= {0, 0, -1, 1};
int dy[]= {1, -1, 0, 0};

void bfs (vector<string> &board, vector< vector<bool> > &check, int x, int y) {
    if (check[y][x] || board[y][x] != 'S') {
        return ;
    }
    check[y][x] = true;
    queue< pair<int, int> > q;
    q.push(make_pair(x, y));
    
    while(!q.empty()) {
        int _x, _y;
        tie(_x, _y) = q.front(); q.pop();

        for (int i=0; i<4; i++) {
            int nx = _x + dx[i];
            int ny = _y + dy[i];
            
            if (nx>=0 && nx<w && ny>=0 && ny<h) {
                if (check[ny][nx])
                    continue;
                if (board[ny][nx] == 'T') {
                    board[ny][nx] = 'S';
                    check[ny][nx] = true;
                    q.push(make_pair(nx, ny));
                }
            }
        }
    }
    return ;
}

int main() {
  while (true) {
    cin >> h >> w;
    if (h==0 && w==0) {
        break;
    }
    cout << h << w;
    vector<string> board(h);
    vector< vector<bool> > check(h, vector<bool>(w, false));
    for (int i=0; i<h; i++) {
        cin >> board[i];
    }
    for (int k=0; k<h; k++) {
        for (int l=0; l<w; l++) {
            bfs(board, check, l, k);
        }
    }

    for (int k=0; k<h; k++) {
      cout << board[k] << endl;
    }
  }
  return (0);
}

input输入

3 4
T..
TST
..T
TTT
5 5
T.T.T
.T.T.
..S..
.T.T.
T.T.T
0 0

output输出在此处输入图片说明

输入首先给出宽度,而不是高度。

    cin >> w >> h;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM