2262我照你的思路建了高斯消元,不知为什么一直错了?能帮我看看吗?
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int MAXN = 20;
struct point_T {
int x, y;
};
point_T st, ed[MAXN * MAXN];
char map[MAXN][MAXN];
int board[MAXN][MAXN];
int row, col, cnt;
double mat[MAXN * MAXN][MAXN * MAXN];
int dir[4][2] = { {1, 0}, {-1, 0}, {0, -1}, {0, 1} };
bool ok(int x, int y) {
return x >= 0 && x < row && y >= 0 && y < col && (map[x][y] == '@' || map[x][y] == '.' || map[x][y] == '$');
}
void floodfill(int x, int y) {
board[x][y] = ++ cnt;
for(int i = 0; i < 4; i ++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(ok(tx, ty) && board[tx][ty] == -1) {
floodfill(tx, ty);
}
}
}
bool gauss(int n) {
int i, j, row, idx;
double buf, maxx;
for(row = 0; row < n; row ++) {
for(maxx = 0, i = row; i < n; i ++) {
if(maxx < fabs(mat[i][row])) {
maxx = fabs(mat[i][row]);
idx = i;
}
}
if(maxx == 0) return false;
if(idx != row) {
for(i = row; i <= n; i ++)
swap(mat[row][i], mat[idx][i]);
}
for(i = row + 1; i < n; i ++) {
buf = mat[i][row] / mat[row][row];
for(j = row; j <= n; j ++)
mat[i][j] -= buf * mat[row][j];
}
}
for(i = n - 1; i >= 0; i --) {
for(j = i + 1; j < n; j ++)
mat[i][n] -= mat[i][j] * mat[j][j];
mat[i][i] = mat[i][n] / mat[i][i];
}
return true;
}
int main() {
int i, j, k, l, cn;
while(scanf("%d%d", &row, &col) != EOF) {
cn = 0;
for(i = 0; i < row; i ++) {
scanf("%s", map[i]);
for(j = 0; j < col; j ++) {
if(map[i][j] == '@') {
st.x = i;
st.y = j;
}else if(map[i][j] == '$') {
ed[cn].x = i;
ed[cn].y = j;
cn ++;
}
}
}
memset(board, -1, sizeof(board));
cnt = -1;
floodfill(st.x, st.y);
for(i = 0; i < cn; i ++) {
if(board[ed[i].x][ed[i].y] != -1)
break;
}
if(i == cn) {
printf("-1\n");
continue;
}
memset(mat, 0, sizeof(mat));
int now, tx, ty, num;
for(i = 0; i < row; i ++) {
for(j = 0; j < col; j ++) {
if(board[i][j] != -1) {
now = board[i][j];
num = 0;
for(k = 0; k < 4; k ++) {
tx = i + dir[k][0];
ty = j + dir[k][1];
if(ok(tx, ty)) {
num ++;
mat[now][board[tx][ty]] = -1;
}
mat[now][now] = num;
mat[now][cnt + 1] = num;
}
}
}
}
for(i = 0; i < cn; i ++) {
l = board[ed[i].x][ed[i].y];
memset(mat[l], 0, sizeof(mat[l]));
mat[l][l] = 1;
}
if(gauss(cnt + 1))
printf("%.6lf\n", mat[board[st.x][st.y]][board[st.x][st.y]]);
else
printf("-1\n");
}
return(0);
}
回复 更多评论