用一个整形矩阵matrix表示一个网格,1代表有路,0代表无路,每一个位置只要不越界,都有上下左右四个方向,求从最左上角到右下角的最短通路值
例如,matrix为:
1 0 1 1 1
1 0 1 0 1
1 1 1 0 1
0 0 0 0 1
通路只有一条,由12个1构成,所以返回12
[要求]
时间复杂度为,空间复杂度为
第一行两个整数N,M表示矩形的长宽
接下来N行,每行一个长度为M的字符串表示矩形
输出一个整数表示最小步数
若从(1, 1)无法到达(n, m)请输出-1
4 5 10111 10101 11101 00001
12
4 5 11011 11111 11111 00001
8
#include <stdio.h> #include <stdlib.h> #define not ! typedef struct Coordintate { int x; int y; } Coord; // function prototype void printGrid(int* *grid, const int kRows, const int kCols); int breadth_first_search_algorithm(int* *grid, const int kRows, const int kCols); int main(const int argc, const char* const argv[]) { int m, n; fscanf(stdin, "%d %d\n", &m, &n); int grid[m][n]; // 逻辑上两维的, 但在内存布局中二维数组是按一维线性连续存储的。 int x, y; char str[n + 1]; for (y = 0; y < m ; ++y) { gets(str); for (x = 0; x < n; ++x) *(*(grid + y) + x) = *(str + x) - 48; } int* rows_of_grid[m]; // 行指针 for (y = 0; y < m; ++y) *(rows_of_grid + y) = grid + y; // printGrid(rows_of_grid, m, n); fprintf(stdout, "%d", breadth_first_search_algorithm(rows_of_grid, m, n)); return 0; } int breadth_first_search_algorithm(int* *grid, const int kRows, const int kCols) { Coord q[kRows * kCols]; // 队列的大小由算法的时简复杂度决定,每个单位格最多入队出队一次! int front = 0, rear = 0; *(q + rear++) = (Coord) {.x = 0, .y = 0}; **grid = 0; // mark as visited static const int dirs[] = { 0, -1, 0, 1, 0 }; Coord coord; int i, x, y, nx, ny, steps = 0; while (front < rear) { size_t s = rear - front; while (s--) { coord = *(q + front++); x = coord.x, y = coord.y; if (x == kCols - 1 && y == kRows - 1) return steps + 1; for (i = 0; i < 4; ++i) { nx = x + *(dirs + i), ny = y + *(dirs + i + 1); if (nx < 0 || ny < 0 || nx == kCols || ny == kRows || !*(*(grid + ny) + nx)) continue; *(q + rear++) = (Coord) {.x = nx, .y = ny}; *(*(grid + ny) + nx) = 0; // mark as visited } } ++steps; } return -1; } void printGrid(int* *grid, const int kRows, const int kCols) { int x, y; for (y = 0; y < kRows; ++y) { for (x = 0; x < kCols; ++x) printf("%d ", *(*(grid + y) + x)); fputc(10, stdout); } }