java - 动态规划 - 图论

标签 java c++ algorithm graph dynamic-programming

You are in a large NxN grid with (2 <= N <= 100), numbered from (1, 1) to (N,N). Each of these rooms except (1,1), is considered to be turned 'off'. Your goal is to turn on as many rooms as possible.

You start in room (1,1), the only room that is initially 'on'. In some rooms, you will find light switches that you can use to switch the state of other rooms; for example there might be a switch in room (1,1) that toggles the state of room (1,2) between on and off. You can only travel through 'on' rooms, and can only move from a room (x,y) to its four adjacent neighbors (x−1,y), (x+1,y), (x,y−1) and (x,y+1) (or possibly fewer neighbors if this room is on the boundary of the grid).

Find the maximum number of rooms you can turn 'on'.

An example: The first line of input contains integers N and M (1≤M≤20,000).

The next M lines each describe a single light switch with four integers x, y, a, b, that a switch in room (x,y) can be used to toggle the state in room (a,b). Multiple switches may exist in any room, and multiple switches may toggle the state of any room.

Output: A single line giving the maximum number of rooms you can turn 'on'.

SAMPLE INPUT:

3 6
1 1 1 2
2 1 2 2
1 1 1 3
2 3 3 1
1 3 1 2
1 3 2 1

SAMPLE OUTPUT:

5

我自己解决了这个例子。我发现的最大情况是当你在 (1,1) 时,你打开 (1,2) 和 (1,3)。然后您转到 (1,3) 并打开 (2,1)。然后您前往 (2,1) 并打开 (2,2)。但是,您无法到达 (2,3),因为它仍然处于“关闭”状态。这样最多可以有 5 个“在线”房间。

到目前为止我的方法:

我认为这可能是一个动态规划或贪心规划。由于 N 的界限很低,我想每次访问一个节点时,您都​​会更新可能访问的地方的数量。也可能有一种方法,您只尝试找到打开开关的地方并尝试前往那里。

你能给我指出一个算法来解决这个问题,也许还有一些伪代码,因为我对这些类型的问题有点陌生。

最佳答案

这可以通过修改图的广度优先搜索来解决。首先,从当前房间点亮所有可能的房间是有意义的。要点亮最大数量的房间,我们必须找到从(1,1)可以到达的所有房间(意思是有一条从(1,1)开始的路径经过点亮rooms) 然后 rooms lited up 是可以从这些“可达”房间中的每一个房间点亮的所有房间的 union 。我们一个一个探索可达的房间,找到可以点亮的房间。这可能会为我们提供更多可达的房间。

完整的伪代码是:

queue Q
Q.push (1,1) // room (1,1) reachable
set litupRooms
litupRooms.push(1,1) // room (1,1) is lit up
set visitedRooms
while (Q is not empty)
  room r = Q.pop ()
  if r is in visitedRooms
    continue
  add r to visitedRooms
  for every room that can be lit up from r
    if it is already lit up
      continue
    add it to litupRooms 
    push it to Q if it is adjacent to a room already visited
  for every adjacent room of r
    push it to Q if it is lit up and not visited
return the size of litupRooms

关于java - 动态规划 - 图论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256555/

相关文章:

python - 在 Python 中合并重叠区间

java - 线程中出现异常 "main"java.land.NullPointerException

java - microsoft-translator-api- 检索翻译时出错 : status code 400 in Java

c++ - Qt如何根据另一个ComboBox中的选定选项设置ComboBox的值

java - 我有 2 个排序的整数数组,如何在 O(logn) 时间内找到第 k 个最大的项目?

处理歧义的算法或数据结构

java - 通过构造函数参数 0 : No qualifying bean of type - Spring boot 表示的未满足的依赖关系

java - 如何在JPanel中使用JTabbedPane?

c++ - GetVersionEx 弃用 - 如何从较新的 API 获取产品类型 (VER_NT_DOMAIN_CONTROLLER)

c++ - 如何引用作为模板参数传递的派生类中定义的类型?