Posts

Showing posts with the label 图找最短路径

803. Shortest Distance from All Buildings (和573. Build Post Office II一模一样)

Code ( Language :C++) Edit class Solution { public : /** * @param grid: the 2D grid * @return: the shortest distance */ const vector < int > dx = { -1 , 1 , 0 , 0 }; const vector < int > dy = { 0 , 0 , -1 , 1 }; const int dir = 4 ; struct node { int x, y; node( int a, int b){ x = a; y = b; } }; int shortestDistance ( vector < vector < int >> &grid) { // write your code here // BFS; target入栈;target挨个入栈(对比663. Walls and Gates //一次全入);多个状态量加持; const int m = grid.size(); if (m == 0 ){ return 0 ; } const int n = grid[ 0 ].size(); int totalTarget = 0 ; // status record vector < vector < int >> dist(m, vector < int >(n, 0 )); vector < vector < int >> cnt(m, vector < int >(n, 0 )); f...

663. Walls and Gates

Code ( Language :C++) Edit class Solution { public : /** * @param rooms: m x n 2D grid * @return: nothing */ struct node { int x, y; node( int a, int b){ x = a; y = b; } }; const vector < int > dx = { -1 , 1 , 0 , 0 }; const vector < int > dy = { 0 , 0 , -1 , 1 }; const int dir = 4 ; void wallsAndGates ( vector < vector < int >> &rooms) { // write your code here //BFS 层层剥洋葱;target入栈;全部target入栈 const int m = rooms.size(); if (m == 0 ){ return ; } const int n = rooms[ 0 ].size(); std :: queue <node> q; for ( int i = 0 ; i < m; i++){ for ( int j = 0 ; j < n; j++){ if (rooms[i][j] == 0 ){ q.push(node(i, j)); } } } // BFS with queue 模板 while (!q...