/* VIM: let b:lcppflags="-std=c++14 -O2 -pthread" VIM: let b:wcppflags="/O2 /EHsc /DWIN32" VIM-: let b:argv="" */ #include #include #include #include #include /* FB On-site March Q: Find number of Islands. XXXOO OOOXX XXOOX Return 3 islands. 1 1 1 O O O O O 2 2 3 3 O O 2 */ int number_of_islands( const std::vector& board ) { auto n = board.size(); auto m = board.front().size(); std::unordered_map g; auto idx = [m](size_t i, size_t j){ return i*m+j; }; auto root = [&g](size_t idx){ for (; g[idx] != idx; idx = g[idx] ); return idx; }; for (size_t i = 0; i < n; ++i ){ for (size_t j = 0; j < m; ++j){ if (board[i][j] == 'x'){ if (j>0 && board[i][j-1] == 'x'){ g[idx(i,j)]=g[idx(i,j-1)]; if (i>0 && board[i-1][j] == 'x'){ g[root(idx(i-1,j))]=g[idx(i,j)]; } } else if (i>0 && board[i-1][j] == 'x'){ g[idx(i,j)]=g[idx(i-1,j)]; } else { g[idx(i,j)]=idx(i,j); } } } } int count = 0; for ( const auto& node: g){ if ( node.first == node.second ){ ++count; } } return count; } int main ( void ) {try{ std::cout << number_of_islands({ "xxxoo", "oooxx", "xxoox" }) << std::endl; std::cout << number_of_islands({ ".xx..", "xx...", "xxxxx" }) << std::endl; std::cout << number_of_islands({ "....x", "....x", "xxxxx" }) << std::endl; std::cout << number_of_islands({ "xxxxx", "xxxxx", "xxxxx" }) << std::endl; std::cout << number_of_islands({ "xxxxx", "....x", "xxx.x", "x...x", "xxxxx" }) << std::endl; return 0; } catch ( const std::exception& e ) { std::cerr << std::endl << "std::exception(\"" << e.what() << "\")." << std::endl; return 2; } catch ( ... ) { std::cerr << std::endl << "unknown exception." << std::endl; return 1; }}