#include<stdio.h>
int main(){
int R, C, k, m;
scanf("%d %d %d %d", &R, &C, &k, &m);
int city[52][52];
int city_move[52][52];
//將city[R][C]周圍以-1建立圍牆,避免遷移時出界
for(int i = 0; i < R+1; i++){
for(int j = 0; j < C+1; j++){
city[i][j]= -1;
}
}
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
scanf("%d", &city[i][j]);
}
}
for(int day = 0; day < m; day++){//模擬m天後人口遷移分布
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
city_move[i][j] = city[i][j];//將原陣列值帶入另一個陣列內
}
}
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
if(city[i][j] == -1){
continue;
}
//上移
if(city[i-1][j] >= 0){
city[i-1][j] = city[i-1][j] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
//右移
if(city[i][j+1] >= 0){
city[i][j+1] = city[i][j+1] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
//下移
if(city[i+1][j] >= 0){
city[i+1][j] = city[i+1][j] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
//左移
if(city[i][j-1] >= 0){
city[i][j-1] = city[i][j-1] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
}
}
}
//求人口最大值與人口最小值
int minimum = -1, maximum = -1;
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
if(city[i][j] >= 0){
if(minimum < 0 || city[i][j] < minimum){
minimum = city[i][j];
}
if(maximum > 0 || city[i][j] > maximum){
maximum = city[i][j];
}
}
}
}
printf("%d\n%d", minimum, maximum);
}
#include
int main(){
int R, C, k, m;
scanf("%d %d %d %d", &R, &C, &k, &m);
int city[52][52];
int city_move[52][52];
//將city[R][C]周圍以-1建立圍牆,避免遷移時出界
for(int i = 0; i < R+1; i++){
for(int j = 0; j < C+1; j++){
city[i][j]= -1;
}
}
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
scanf("%d", &city[i][j]);
}
}
for(int day = 0; day < m; day++){//模擬m天後人口遷移分布
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
city_move[i][j] = city[i][j];//將原陣列值帶入另一個陣列內
}
}
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
if(city[i][j] == -1){
continue;
}
//上移
if(city[i-1][j] >= 0){
city[i-1][j] = city[i-1][j] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
//右移
if(city[i][j+1] >= 0){
city[i][j+1] = city[i][j+1] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
//下移
if(city[i+1][j] >= 0){
city[i+1][j] = city[i+1][j] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
//左移
if(city[i][j-1] >= 0){
city[i][j-1] = city[i][j-1] + city_move[i][j] / k;
city[i][j] = city[i][j] - city_move[i][j] / k;
}
}
}
}
//求人口最大值與人口最小值
int minimum = -1, maximum = -1;
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
if(city[i][j] >= 0){
if(minimum < 0 || city[i][j] < minimum){
minimum = city[i][j];
}
if(maximum > 0 || city[i][j] > maximum){
maximum = city[i][j];
}
}
}
}
printf("%d\n%d", minimum, maximum);
}
看起來上移和左移的時候i-1或j-1可能會是負數?