#46270: c++解


boomrock46@gmail.com (310622(林子誠)一資甲)

學校 : 國立臺中高級工業職業學校
編號 : 289724
來源 : [60.198.76.202]
最後登入時間 :
2025-10-02 22:52:53

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, m;
    int dx[4] = {0, 0, -1, 1};
    int dy[4] = {-1, 1, 0, 0};
    int a[1000][1000];
    bool visited[1000][1000] = {0};
    int sum = 0;

    cin >> n >> m;

    int x = 0, y = 0, min_val = 1e6;

    for (int i = 0; i < n; i++) { // y
        for (int j = 0; j < m; j++) { // x
            cin >> a[i][j];

            if (a[i][j] < min_val) {
                min_val = a[i][j];
                x = j;
                y = i;
            }
        }
    }

    int nx = -1, ny = -1, nv = 0;

    while (1) {
        sum += a[y][x];
        visited[y][x] = 1;

        int nextx = -1, nexty = -1, nv = 1e6;

        for (int d = 0; d < 4; d++) {
            int nx = x + dx[d];
            int ny = y + dy[d];

            if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[ny][nx]) {
                if (a[ny][nx] < nv) {
                    nv = a[ny][nx];
                    nextx = nx;
                    nexty = ny;
                }
            }
        }
        if (nextx == -1) break;
        x = nextx;
        y = nexty;
    }
    cout << sum;
}