We need to find the distance between the two Farthest Points in the graph. The longest path starting from each brute force enumeration is obviously not feasible. Another endpoint of the longest path starting from any point A is called B, so B is an endpoint of the global longest path. Then, a wide search starts from, and the farthest point is C. BC is the longest path in the graph. [Cpp] # include <iostream> # include <math. h> # include <stdio. h> # include <string. h> # include <queue> # include <algorithm> # include <stack> using namespace std; int column, row; int map [1002] [1002]; int dis [1002] [1002]; int disx [4] = {, 0,-1}; int disy [4] = {,-}; int maxX; int maxY; struct Point {int x; int y ;}; int bfs (int startx, int starty) {queue <Point> p; Point nex, temp; maxX = startx; MaxY = starty; int maxP = 0; nex. x = startx; nex. y = starty; p. push (nex); while (! P. empty () {temp = p. front (); p. pop (); for (int I = 0; I <4; I ++) {int tempx = temp. x + disx [I]; int tempy = temp. y + disy [I]; if (tempx> = 0 & tempx <row & tempy> = 0 & tempy <column) {if (map [tempx] [tempy] = 1) {map [tempx] [tempy] = 2; dis [tempx] [tempy] + = dis [temp. x] [temp. y] + 1; nex. x = tempx; nex. y = tempy; p. push (nex); if (dis [tempx] [tempy]> maxP) {maxP = dis [tempx] [tempy]; maxX = tempx; maxY = tempy ;}}}return maxP;} int main () {# ifndef ONLINE_JUDGE freopen ("in.txt", "r", stdin); # endif int t; char c; scanf ("% d", & t); int startx, starty; while (t --) {memset (map, 0, sizeof (map )); memset (dis, 0, sizeof (dis); scanf ("% d", & column, & row); for (int I = 0; I <row; I ++) {for (int j = 0; j <column; j ++) {scanf ("% c", & c); if (c = '. ') {map [I] [j] = 1 ;}}for (int I = 0; I <row; I ++) {int flag = 0; for (int j = 0; j <column; j ++) {if (map [I] [j] = 1) {flag = 1; startx = I; starty = j; break ;}}if (flag = 1) {break ;}} map [startx] [starty] = 2; // mark as bfs (startx, starty) accessed; // restore the original map for (int I = 0; I <row; I ++) {www.2cto.com for (int j = 0; j <column; j ++) {if (map [I] [j] = 2) {map [I] [j] = 1 ;}} memset (dis, 0, sizeof (dis); printf ("Maximum rope length is % d. \ n ", bfs (maxX, maxY);} return 0 ;}