1126 地图分析
#define MAX_NUMS 1000000
typedef struct Node_ {
int x;
int y;
}Node;
typedef struct Queue_ {
Node arr[MAX_NUMS];
int front;
int rear;
}Queue;
void QueueInit(Queue* queue)
{
queue->front = 0;
queue->rear = 0;
}
bool Full(Queue* queue)
{
if ((queue->rear + 1) % MAX_NUMS == queue->front) {
return true;
}
return false;
}
bool Empty(Queue* queue)
{
return queue->front == queue->rear;
}
void QueuePush(Queue* queue, Node node)
{
if (!Full(queue)) {
queue->arr[queue->rear] = node;
queue->rear = (queue->rear + 1) % MAX_NUMS;
}
}
void QueuePop(Queue* queue)
{
if (!Empty(queue)) {
queue->front = (queue->front + 1) % MAX_NUMS;
}
}
void QueueClear(Queue* queue)
{
queue->front = 0;
queue->rear = 0;
}
Node QueueTop(Queue* queue)
{
return queue->arr[queue->front];
}
int QueueLength(Queue que)
{
return (que.rear - que.front + MAX_NUMS) % MAX_NUMS;
}
int maxDistance(int** grid, int gridSize, int* gridColSize){
if (!grid) {
return -1;
}
int row = gridSize;
int col = *gridColSize;
Queue q;
QueueInit(&q);
int pass[100][100] = {0};
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j]) {
Node land = {i, j};
pass[i][j] = 1;
printf(" pass push[%d][%d]\n",i,j);
QueuePush(&q, land);
}
}
}
int res = 0;
while(!Empty(&q)) {
int curLen = QueueLength(q);
for (int i = 0; i < curLen; i++) {
Node temp = QueueTop(&q);
QueuePop(&q);
if (((temp.x - 1) >= 0) && !pass[temp.x - 1][temp.y]) { //向上
pass[temp.x - 1][temp.y] = 1;
Node land = {temp.x - 1, temp.y};
printf("start from [%d][%d], push[%d][%d]\n", temp.x, temp.y, temp.x - 1, temp.y);
QueuePush(&q, land);
}
if (((temp.x + 1) < row) && !pass[temp.x + 1][temp.y]) { //向下
pass[temp.x + 1][temp.y] = 1;
Node land = {temp.x + 1, temp.y};
printf("start from [%d][%d], push[%d][%d]\n", temp.x, temp.y, temp.x + 1, temp.y);
QueuePush(&q, land);
}
if (((temp.y + 1) < col) && !pass[temp.x][temp.y + 1]) { //向右
pass[temp.x][temp.y + 1] = 1;
Node land = {temp.x, temp.y + 1};
printf("start from [%d][%d], push[%d][%d]\n", temp.x, temp.y, temp.x, temp.y + 1);
QueuePush(&q, land);
}
if (((temp.y - 1) >= 0) && !pass[temp.x][temp.y - 1]) { //向左
pass[temp.x][temp.y - 1] = 1;
Node land = {temp.x, temp.y - 1};
printf("start from [%d][%d], push[%d][%d]\n", temp.x, temp.y, temp.x, temp.y - 1);
QueuePush(&q, land);
}
}
int i = 0;
for (; i < row; i++) {
int j = 0;
for (; j < col; j++) {
if (pass[i][j] == 0) {
printf("pass[%d][%d] is 0\n", i, j);
break;
}
}
if (j < col) {break;}
}
if (i >= row) {
return (res == 0) ? -1 : (res + 1);
}
res++;
}
return -1;
}