-
Notifications
You must be signed in to change notification settings - Fork 0
/
swexpert_1249.cpp
55 lines (50 loc) · 1.1 KB
/
swexpert_1249.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>
#include<queue>
#define MAX_N 100
using namespace std;
int map[MAX_N][MAX_N];
bool visited[MAX_N][MAX_N];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int N;
int dist[MAX_N][MAX_N];
void bfs() {
queue<pair<int,int>> q;
q.push(make_pair(0, 0));
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < N&&ny < N) {
if (!visited[nx][ny] || dist[nx][ny] > dist[x][y] + map[nx][ny]) {
dist[nx][ny] = dist[x][y] + map[nx][ny];
q.push(make_pair(nx, ny));
visited[nx][ny] = true;
}
}
}
}
}
int main() {
int T;
cin >> T;
for (int tc = 1; tc <= T; tc++) {
// data input
cin >> N;
char line[MAX_N];
for (int i = 0; i < N; i++) {
cin >> line;
for (int j = 0; j < N; j++) {
map[i][j] = line[j] - '0';
dist[i][j] = visited[i][j] = false;
}
}
// solve
bfs();
// data output
cout << "#" << tc << " " << dist[N - 1][N - 1] << endl;
}
}